What best practices should be followed when handling SQL queries in PHP code?

When handling SQL queries in PHP code, it is essential to use prepared statements to prevent SQL injection attacks. Prepared statements separate SQL code from user input, making it impossible for malicious input to alter the SQL query. Additionally, always sanitize user input to remove any potentially harmful characters before using it in a query.

// Example of using prepared statements in PHP to handle SQL queries securely

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

// Prepare a SQL statement with a placeholder for user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the user input to the placeholder
$username = $_POST['username'];
$stmt->bindParam(':username', $username);

// Execute the prepared statement
$stmt->execute();

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