This is to create a community learning resource. The goal is to have examples of good code that do not repeat the awful mistakes that can so often be found in copy/pasted PHP code. I have requested it be made Community Wiki.
This is not meant as a coding contest. It's not about finding the fastest or most compact way to do a query - it's to provide a good, readable reference especially for newbies.
Every day, there is a huge influx of questions with really bad code snippets using the mysql_*
family of functions on Stack Overflow. While it is usually best to direct those people towards PDO, it sometimes is neither possible (e.g. inherited legacy software) nor a realistic expectation (users are already using it in their project).
Common problems with code using the mysql_*
library include:
- SQL injection in values
- SQL injection in LIMIT clauses and dynamic table names
- No error reporting ("Why does this query not work?")
- Broken error reporting (that is, errors always occur even when the code is put into production)
- Cross-site scripting (XSS) injection in value output
Let's write a PHP code sample that does the following using the mySQL_* family of functions:
- Accept two POST values,
id
(numeric) andname
(a string) - Do an UPDATE query on a table
tablename
, changing thename
column in the row with the IDid
- On failure, exit graciously, but show the detailed error only in production mode.
trigger_error()
will suffice; alternatively use a method of your choosing - Output the message "
$name
updated."
And does not show any of the weaknesses listed above.
It should be as simple as possible. It ideally doesn't contain any functions or classes. The goal is not to create a copy/pasteable library, but to show the minimum of what needs to be done to make database querying safe.
Bonus points for good comments.
The goal is to make this question a resource that a user can link to when encountering a question asker who has bad code (even though it isn't the focus of the question at all) or is confronted with a failing query and doesn't know how to fix it.
To pre-empt PDO discussion:
Yes, it will often be preferable to direct the individuals writing those questions to PDO. When it is an option, we should do so. It is, however, not always possible - sometimes, the question asker is working on legacy code, or has already come a long way with this library, and is unlikely to change it now. Also, the mysql_*
family of functions is perfectly safe if used properly. So no "use PDO" answers here please.
My stab at it. Tried to keep it as simple as possible, while still maintaining some real-world conveniences.
Handles unicode and uses loose comparison for readability. Be nice ;-)
I decided to jump the gun and just put something up. It's something to start with. Throws an exception on error.
form.php
list.php
Looks like my other answer missed the aim of the question.
(this one doesn't meet some requirements either, but as it can be seen, no safe solution can be achieved without implementing a function to process placeholders, which are being the cornerstone of the safe queries)
So, here is another attempt to post concise solution to make mysql queries safe yet handy.
A function I wrote long time ago and it served me well until I moved to the corporative standard OOP-based solution.
There was 2 goals to pursue for: security and ease of use.
First one achieved by implementing placeholders.
Second one achieved by implementing placeholders and different result types.
The function surely not ideal one. Some drawbacks are:
%
chars have to be placed in the query directly as it's using printf syntax."ORDER BY $field"
case have to be handled manually!Yet it is good, safe and concise, no need to install a whole library.
usage examples
As it can be seen from the above examples, the main difference from all the codes ever posted in Stackoverflow, both safety and data retrieval routines are encapsulated in the function code. So, no manual binding, escaping/quoting or casting, as well as no manual data retrieval.
combined with other helper function
used like this
it may cover almost every need, including the example case from the OP.
And some explanation of comments:
With using mysql_select_db you can create errors, and it will be not so easy to find and fix them.
For example, in some script you will set db1 as database, but in some function you need to set db2 as database.
After calling this function, database will be switched, and all following queries in script will be broken or will broke some data in wrong database (if names of tables and columns will coincide).
Some names of columns can be also SQL-keywords, and using "`" symbol will help with that.
Also, all string-values, inserted to query, should be quoted by ' symbol.
//always use htmlspecialchars() to sanitize user's data in output
It will help you to prevent XSS-attacks.