What are some best practices for constructing and executing MySQL queries in PHP?

When constructing and executing MySQL queries in PHP, it is important to use parameterized queries to prevent SQL injection attacks. This involves using prepared statements and binding parameters to ensure that user input is properly sanitized. Additionally, it is recommended to handle errors gracefully by checking for query execution errors and logging them appropriately.

// Example of constructing and executing a MySQL query in PHP with parameterized queries

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

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

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

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

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

// Handle errors
if (!$results) {
    // Log error message
    error_log('Error executing query: ' . $stmt->errorInfo()[2]);
}