What are some alternative methods for constructing MySQL queries in PHP?

When constructing MySQL queries in PHP, using prepared statements is a more secure method compared to directly inserting user input into the query string. Prepared statements help prevent SQL injection attacks by separating the query logic from the user input.

// Using prepared statements to construct MySQL queries in PHP
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

// Bind parameters
$stmt->bindParam(':username', $username);

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

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