Skip to content
PHP Logo

How can SQL injection be prevented in PHP scripts?

SQL injection can be prevented in PHP scripts by using prepared statements with parameterized queries. This method ensures that user input is treated as data rather than executable code, thus preventing attackers from injecting malicious SQL queries into the database.

php
// Using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');

$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute(['username' => $_POST['username']]);
$user = $stmt->fetch();