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
in VALUES
, 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 a SQL 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:Add 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:get_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:
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.explicitly written 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:$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: