Skip to content
PHP Logo

How can SQL injection be prevented when inserting data into a database using PHP?

SQL injection can be prevented when inserting data into a database using PHP by using prepared statements with parameterized queries. This method separates the SQL query and the user input, preventing malicious SQL code from being executed.

php
// Establish connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with a placeholder for user input
$stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");

// Bind the user input to the placeholders
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);

// Execute the prepared statement
$stmt->execute();