How can the use of prepared statements in PHP improve security and efficiency when interacting with a MySQL database?
Using prepared statements in PHP can improve security by preventing SQL injection attacks, as it separates the SQL query from the user input. This also improves efficiency by allowing the database to compile the query only once and execute it multiple times with different parameters. Prepared statements can be easily implemented in PHP using the PDO (PHP Data Objects) extension.
// Establish a connection to the MySQL database
$pdo = new PDO('mysql:host=localhost;dbname=database_name', '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
$stmt->bindParam(':username', $_POST['username']);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();