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 thenamecolumn 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 "
$nameupdated."
And does not show any of the weaknesses listed abo