I'm trying to insert values into a table of contents. It works fine if there are no PHP variables in VALUES. However, when I put the variable$type
inVALUES
, it doesn't work. What did i do wrong?
$type = 'testing'; mysql_query("INSERT INTO contents (type, reporter, description) VALUES($type, 'john', 'whatever')");
To avoid SQL injection, the insert statement will be:
The rules for adding PHP variables in any MySQL statement are simple and straightforward:
1. Use prepared statements
This rule applies to 99% of queries, and it also applies to your query. Any variable that represents aSQL data literal(or simply, a SQL string or number) must be added via a prepared statement. Without exception.
This method consists of four basic steps:
mysqli
Current PHP versions allow you to prepare/bind/execute in a single call: If you have an older version of PHP, you must do prepare/bind/execute explicitly: This code is a bit complex, but a detailed explanation of all these operators can be found in my articleAdd data literal
How to run an INSERT query using Mysqli, as well as a solution that can greatly simplify the process.
For SELECT queries, you can use the same method as above: However, if you have an older version of PHP, you will need to do the prepare/bind/execute routine, and also call theget_result()
Use PDO to add data literalsmethod in order to get a familiar
from it mysqli_result, from which data can be extracted in the usual way:
In PDO, we can merge the binding and execution parts together, which is very convenient. PDO also supports named placeholders, which some people find very convenient. 2. Use whitelist filtering Any other query parts, such as SQL keywords, table or field names, or operators, must be filtered through a
whitelist.
Sometimes we have to add a variable that represents another part of the query, such as a keyword or identifier (database, table or field name). This is a rare situation, but it's best to be prepared. In this case, your variable must be checked against the list of valuesexplicitlywritten in your script. This is explained in detail in my other articleAdd field names in the ORDER BY clause based on user selection:
This is an example: After code like this, the$direction
The last thing to mention is that identifiers must also be formatted according to the specific database syntax. For MySQL, the identifier should be surrounded byand
$orderbyvariables can be safely put into the SQL query because they will either be equal to one of the allowed variants or they will throw An error occurred.
backtick
characters. So the final query string for our ORDER BY example should be: