What are the best practices for handling SQL queries in PHP to ensure efficient and secure database interactions?
To ensure efficient and secure database interactions in PHP, it is important to use prepared statements to prevent SQL injection attacks and improve performance by reusing query execution plans. Additionally, it is recommended to validate and sanitize user input before including it in SQL queries to prevent potential security vulnerabilities.
// 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, PDO::PARAM_STR);
// Sanitize and validate user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Loop through the results
foreach ($results as $row) {
// Output or process the data
}