How to prevent SQL injections in PHP

Ask a question
1

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?

offer bounty
add comment

1 Answer

1

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]";
$stmt->execute();

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

Thanks, Hidely
https://twitter.com/hid3ly

add comment

Your Answer