How can the use of prepared statements improve security in PHP code?
Using prepared statements in PHP code can improve security by preventing SQL injection attacks. Prepared statements separate SQL logic from user input, which allows the database to distinguish between code and data. This prevents malicious users from injecting SQL code into input fields and manipulating the database.
// Connect to database
$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', $_POST['username']);
// Execute the statement
$stmt->execute();
// Fetch results
$results = $stmt->fetchAll();