Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Mar 2009
    Thanked 0 Times in 0 Posts

    Regarding sprintf()

    why would i use sprintf() for query like insert at databaseeeeeee

  • #2
    Regular Coder
    Join Date
    Oct 2008
    Thanked 22 Times in 22 Posts
    Because sprintf ensure the user input is of the datatype you specified.

    The general goal of this is to avoid SQL injection attacks.

    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

    PHP Code:
    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)); 
    Last edited by AlexV; 04-29-2009 at 03:57 PM.


    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts