How to protect your database from SQL injection in PHP ? Here we discussed unique and effective 9 strategies you can follow:

Always Use Prepared Statements (with PDO or MySQLi)

Use parameterized queries instead of directly embedding variables into SQL strings.
This separates user input from SQL logic, blocking injections.

Example:

$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);

Never Trust User Input – Always Sanitize

Even when using prepared statements, sanitize inputs to remove unwanted characters or scripts.

Example:

$username = trim(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING));

Avoid Dynamic SQL in Logic

Don’t construct SQL strings using input variables, its very dangerous.

Avoid this:

$sql = "SELECT * FROM users WHERE id = $_GET[id]";

Use Whitelisting for Column & Table Names

If you use dynamic SQL for column names (name,email etc, for sorting), use strict whitelisting.

Example:

$allowed = ['name', 'email', 'created_at'];
$sort = in_array($_GET['sort'], $allowed) ? $_GET['sort'] : 'name';

Disable Error Display in Production

Don’t show raw database errors to users – attackers can use them for injections! So turn off display_errors.

In php.ini or any code:

ini_set('display_errors', 0);

Use Least Privilege for Database Users

Create a DB user with only necessary permissions, don’t give full access. If only reading data, deny INSERT, UPDATE, DELETE.

Limit Data show

Avoid querying “SELECT *” Only select specific fields, that juat needs for your task.

SELECT name, email FROM users

Log Suspicious Activity’s

Monitor and log failed queries or repeated injection attempts for further analysis or blocking.

Regularly Update PHP & DB Software

Always stay updated to patch any known security vulnerabilities in the PHP engine or MySQL/MariaDB.

Note: Use a Framework or ORM

Frameworks like Laravel, Symfony, or ORMs like Eloquent inherently prevent SQL injections via built-in protections.

Here we se secure and SQL injection-proof PHP example using PD

Add User (Insert)

<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "db_user", "db_pass");

// Optional: Turn on error mode to throw exceptions
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Getting input
$name = trim($_POST['name']);
$email = trim($_POST['email']);

// Insert user securely
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$success = $stmt->execute([$name, $email]);

if ($success)  echo "User added successful!";
else  echo "User add failed!";

?>

Update User (update)

<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "db_user", "db_pass");

// Optional: Turn on error mode to throw exceptions
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Getting input $id = intval($_POST['id']); // Always cast IDs to integer for safety $name = trim($_POST['name']); $email = trim($_POST['email']); // Update user securely $stmt = $pdo->prepare("UPDATE users SET name = ?, email = ? WHERE id = ?"); $success = $stmt->execute([$name, $email, $id]); if ($success) echo "User update successful!"; else echo "update failed!"; ?>

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply