Skip to content
PHP Logo

How can you prevent SQL injection when inserting form data into a database in PHP?

To prevent SQL injection when inserting form data into a database in PHP, you should use prepared statements with parameterized queries. This helps to separate the SQL query logic from the user input data, preventing malicious SQL code from being executed.

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

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

// Bind parameters to the placeholders
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', $_POST['password']);

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