What are some best practices for securely storing and retrieving values from a database in PHP to prevent SQL injection?
To prevent SQL injection in PHP, it is important to use prepared statements with parameterized queries when interacting with a database. This ensures that user input is treated as data rather than executable SQL code, thus preventing malicious SQL injection attacks.
// Establish a connection to the database
$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', $username);
// Execute the statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();