
Top PHP Security Tips for Prevent SQL Injection Attacks
When using Prepared Statements with PDO or MySQLi, user input is not directly added to the query, but is bound separately. As a result, a hacker cannot break SQL even if he wants to. 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';Correct Database User Privileges
Do not give all POWER (such as DROP, DELETE, ALTER on all tables) to the user you are connecting to the database with. Even if the query is ever compromised, the damage will be limited. Always use least Privilege for database users.
- Only grant access to the necessary tables.
- Keep DROP, ALTER, GRANT permissions off unless necessary.
Disable Error Display in Production
If database errors are shown directly to the user, they can understand the table name, column name, etc. 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);Best practice in Production
try {
//// Your DB code
} catch (PDOException $e) {
//// Show custom message
echo "Something went wrong. Please try again later.";
//// Keep the original error in the log file.
error_log($e->getMessage());
}Limit Data show
Avoid querying “SELECT *” Only select specific fields, that juat needs for your task.
SELECT name, email FROM usersLog 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!";
?>Conclusion
Always use Prepared Statement / Parameterized Query (PDO or MySQLi). Never concatenate user input directly into SQL queries. Do input validation and sanitization. Keep database user privileges to a minimum. Hide error messages, just log them. If using an ORM/Framework, follow its security features.





