How can prepared statements be properly implemented in PHP using PDO for secure database queries?
Prepared statements in PHP using PDO can be properly implemented by using placeholders in the SQL query and binding the values to these placeholders. This helps prevent SQL injection attacks by separating the SQL query from the user input data. By using prepared statements, the database engine can distinguish between the actual SQL code and the user input, ensuring secure database queries.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL query with placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the user input data to the placeholders
$stmt->bindParam(':username', $_POST['username']);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Use the results as needed
foreach ($results as $row) {
echo $row['username'] . '<br>';
}