What are the advantages of using prepared statements in PHP for database queries?
When executing SQL queries in PHP, using prepared statements is recommended for security reasons. Prepared statements help prevent SQL injection attacks by separating SQL code from user input, making it impossible for malicious input to alter the SQL query structure. Additionally, prepared statements can improve performance by allowing the database to optimize query execution.
// Using prepared statements to execute a query in PHP
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');
// Prepare a SQL statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind parameters
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
// Execute the query
$stmt->execute();
// Fetch results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Loop through results
foreach ($results as $result) {
// Process each row
}