How to prevent SQL injections in PHP

Ask a question+

If the user submits a form and the values are being used in the SQL query without modifications, then it is open for SQL injections. For example:

$value = $_POST['input_value']; 

mysql_query("INSERT INTO `table` (`column`) VALUES ('$value')");

That’s because the user can input something anything like value’); DROP TABLE table;--, and the query becomes:

INSERT INTO `table` (`column`) VALUES('value'); DROP TABLE table;--')

How is it possible to prevent this from the injection?

add comment

1 Answer


This is a standard SQL attack and is really easy to prevent, and there are many methods to prevent these attacks. One is using prepaid statements:

In a prepaid statement, the query and values are taken. Differently, this is how you will write a prepaid statement:

$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

$firstname = "John";
$lastname = "Doe";
$email = "[email protected]";

Thought be careful writing code, sometimes even with prepaid statements, there can be SQL injections ‘couse with bad logic, ex: https://youtu.be/BTGcasHiI18, https://twitter.com/hid3ly

Hid3ly 30
add comment

Your Answer