What best practices should be followed when constructing complex MySQL queries in PHP to avoid unexpected results?

When constructing complex MySQL queries in PHP, it is essential to use parameterized queries to prevent SQL injection attacks and ensure the security of your application. Additionally, always sanitize user input before including it in the query to avoid unexpected results or errors. Lastly, properly handle errors and exceptions to gracefully handle any issues that may arise during query execution.

// Example of constructing a complex MySQL query in PHP using parameterized queries and input sanitization

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

// User input
$userInput = $_POST['user_input'];

// Prepare the query with placeholders
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the parameter
$stmt->bindParam(':username', $userInput, PDO::PARAM_STR);

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

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

// Handle errors
if (!$results) {
    throw new Exception("Error executing query");
}

// Process the results
foreach ($results as $row) {
    // Do something with the data
}