View Full Version : Regarding sprintf()

04-29-2009, 11:05 AM
why would i use sprintf() for query like insert at databaseeeeeee

04-29-2009, 02:51 PM
Because sprintf ensure the user input is of the datatype you specified.

The general goal of this is to avoid SQL injection attacks (http://en.wikipedia.org/wiki/SQL_injection).

For example you ask in an HTML form for a quantity. The user put aaa instead of a number in the field. If you do nothing you'll end up in trying:

INSERT INTO someTable (qty) VALUES (aaa) which will fail.

If you validate your data with a sprintf %d, aaa will be converted to 0. Still you should validate your data, but at least sprintf ensure the correct datatype for a given value.

Usually sprintf is used with an escape function like mysql_real_escape_string.

Before any SQL query that result from input data you should always
1) Check/validate user data
2) Escape the values entered by the user
3) Use sprintf to ensure datatype integrity

if (is_numeric($user) && $user > 0)
$query = sprintf("SELECT * FROM users WHERE userId= %d AND password= '%s'", mysql_real_escape_string($user), mysql_real_escape_string($password));