What are the best practices for handling database queries in PHP, particularly when it comes to escaping strings and ensuring data integrity?
When handling database queries in PHP, it is crucial to properly escape strings to prevent SQL injection attacks and ensure data integrity. One of the best practices is to use prepared statements with parameterized queries to securely pass data to the database. This method automatically escapes special characters in the input values, reducing the risk of SQL injection vulnerabilities.
// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
// Bind the parameter value
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
// Execute the query
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);