How do I query databases safely and efficiently in PHP?

To query databases safely and efficiently in PHP, you should use prepared statements. This prevents SQL injection and enhances performance by allowing the database to cache the query plan. Below is an example of how to use PDO (PHP Data Objects) for querying a database securely:

<?php // Database connection $host = 'localhost'; $db = 'your_database'; $user = 'your_username'; $pass = 'your_password'; $charset = 'utf8mb4'; $dsn = "mysql:host=$host;dbname=$db;charset=$charset"; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; try { $pdo = new PDO($dsn, $user, $pass, $options); } catch (\PDOException $e) { throw new \PDOException($e->getMessage(), (int)$e->getCode()); } // Using prepared statements $stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email"); $stmt->execute(['email' => 'example@example.com']); $user = $stmt->fetch(); if ($user) { echo "User found: " . $user['name']; } else { echo "User not found."; } ?>

Keywords: PHP database queries safe efficient prepared statements PDO SQL injection