What is the purpose of using prepared statements in PHP and how can they help prevent SQL injection attacks?
Using prepared statements in PHP helps prevent SQL injection attacks by separating SQL logic from user input. This means that the SQL query is precompiled and only the parameters are sent to the database, preventing malicious SQL code from being executed. Prepared statements also automatically escape special characters, further reducing the risk of SQL injection attacks.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username']);
// Execute the statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();