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.
// 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();
Related questions
-
PHP file renaming special characters
-
caching string searches strpos
-
$_POST security risks PHP