How can prepared statements be used in PHP to improve security and efficiency when interacting with a MySQL database?
Prepared statements in PHP can improve security and efficiency when interacting with a MySQL database by separating SQL logic from data input, preventing SQL injection attacks, and reducing the need for repetitive parsing of SQL queries. To use prepared statements, you can use the PDO (PHP Data Objects) extension in PHP to prepare and execute SQL statements with placeholders for parameters.
// Establish a connection to the MySQL database using PDO
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with a placeholder for a parameter
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind a value to the parameter placeholder
$username = 'john_doe';
$stmt->bindParam(':username', $username);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();
// Loop through the results
foreach ($results as $row) {
// Handle each row as needed
}