Backend Development 5 min read

Using MySQLi and PDO to Prevent SQL Injection in PHP

The article explains why directly concatenating user input into SQL queries leads to injection vulnerabilities and demonstrates how to secure PHP database operations using input validation, escaping functions, and prepared statements with MySQLi and PDO, while comparing related sanitization functions.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using MySQLi and PDO to Prevent SQL Injection in PHP

SQL injection occurs when user input is concatenated directly into SQL statements without validation, as shown by the vulnerable example using $id = $_GET['id']; $sql = "SELECT name FROM users WHERE id = $id"; .

Converting the input to an integer with $id = intval($_GET['id']); removes unsafe characters.

String inputs should be sanitized using functions such as addslashes(sprintf("%s", $str)); or mysqli_real_escape_string , and length checks can prevent buffer overflow attacks.

Parameterized queries provide a stronger defense; MySQLi prepared statements can be used as:

$mysqli = new mysqli('localhost','my_user','my_password','world');
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

PDO offers a similar approach:

$sql = 'SELECT name, colour, calories FROM fruit WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql);
$sth->execute([':calories'=>150, ':colour'=>'red']);
$red = $sth->fetchAll();

When custom queries are necessary, a manual preparation function can be written, as illustrated by the prepare() example that validates placeholders and escapes arguments.

The article concludes that security awareness, proper input validation, and using prepared statements are essential to avoid vulnerabilities, and it compares addslashes , mysql_real_escape_string , and mysql_escape_string functions.

addslashes() simply adds backslashes.

mysql_real_escape_string() respects the connection charset but requires a recent PHP version.

mysql_escape_string() does not consider the charset.

SQL injectionprepared statementsPDOmysqli
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.