For many years it was believed in the myth that mysql_real_escape_string
protected from SQL Injection. Time has shown that no, and that in certain scenarios you can perfectly perpetrate an injection even using mysql_real_escape_string
. You can say that this function does not really help to escape from an injection as you might think.
Practice has also shown that the most robust measure to protect against SQL injection are prepared queries.
The strength of this technique is very simple: the query and the data (element that a malicious user can manipulate to inject code) travel separately .
For this reason, prepared queries have bookmarks , which replace the data themselves, as in your query:
SELECT * FROM shops WHERE name = $1
here $1
is a marker that tells the system there is a data, then I tell you the data that is .
Next, with the pg_execute
method, we tell the handler what data it is. If there is something harmful it will be analyzed and rejected, so that the injection is neutralized.
Here:
$result = pg_execute($dbconn, "my_query", array("Joe's Widgets"));
What we say to the manager is something like: what is promised is debt, this is the data that I told you about: Joe's Widgets
... check if everything is ok and execute the query .
If the handler discovers malicious code, it will not execute the query.
This is the core of what are known as prepared queries.
In addition, prepared queries have another advantage, and that is that you can re-use them. The same query that was prepared earlier can be used to select the records that have a name
equal to Clothes Clothes Clothes
.
For more details you can read the question: How to avoid SQL injection in PHP? . In the answer I have given, it is explained why it is convenient to use prepared queries. And we also talk about the necessary configurations to make the code more robust.