How to prevent SQL injections in PHP

Ask a question

If the user submits a form and the values are being used in 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 it is possible to prevent this from injection?

Coin iconoffer bounty
add comment

1 Answer


this is a standerd sql attact, and is really easy to prevent, there are many methord to prevent these attact one of is using prepaid statements:

In a prepaid statements the quary and values are taken differently, this is how you will write a prepaid statements:

$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:

Thanks, Hidely

add comment

Your Answer