How can variables be safely inserted into SQL queries in PHP?

To safely insert variables into SQL queries in PHP, you should use prepared statements with parameterized queries. This method separates the SQL query logic from the data being passed in, preventing SQL injection attacks. Prepared statements automatically handle escaping and quoting of variables, making your code more secure.

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL query with a parameter
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the variable to the parameter
$stmt->bindParam(':username', $username);

// Execute the query
$stmt->execute();

// Fetch results
$results = $stmt->fetchAll();