View Full Version : Regarding sprintf()
04-29-2009, 12:05 PM
why would i use sprintf() for query like insert at databaseeeeeee
04-29-2009, 03: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));
Powered by vBulletin® Version 4.2.2 Copyright © 2017 vBulletin Solutions, Inc. All rights reserved.