Home > Dev > PHP Security > Prepared Statements for SQL Queries

Prepared Statements for SQL Queries

This code uses prepared statements to prevent SQL injection.

function secure_query($pdo, $query, $params) {
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Usage example
$pdo = new PDO('mysql:host=hostname;dbname=database', 'username', 'password');
$query = "SELECT * FROM users WHERE email = :email";
$params = array(':email' => 'user@example.com');
$result = secure_query($pdo, $query, $params);
Back