Jump to content

Sprintf and mysql_real_escape_string....


notepad

Recommended Posts

Hi, I just recently learned about mysql_real_escape_string. So I looked it up in the php.net manual, and I didn't understand one thing:

 

        // Make a safe query
        $query = sprintf("INSERT INTO products (`name`, `description`, `user_id`) VALUES ('%s', '%s', '%d')",
                    mysql_real_escape_string($product_name, $link),
                    mysql_real_escape_string($product_description, $link),
                    $_POST['user_id']);

 

I have never seen this kind of code... I don't understand the '%s' type arguments.  mysql_real_escape_string is simple enough, but I really don't get this part of the example.  I read the page about sprintf on php.net, but I am still just as confused...

 

The way I am using mysql_real_escape_string now is like this(not my code, it was posted by wildteen88):

 

function makeSQLSafe($str)
{
    // check the status of magic_quotes_gpc, if it this returns true 
    // we remove the escaped characters. Allowing for the real escaping 
    // to be done via mysql_real_escape_string
    if(get_magic_quotes_gpc())
    {
        // remove the slashes.
        $str = stripslashes($str);
    }

    $str = mysql_real_escape_string($str);

    return $str;
}

// example usage:
$username = makeSQLSafe($_POST['username']);

 

Any tips?

Link to comment
https://forums.phpfreaks.com/topic/49922-sprintf-and-mysql_real_escape_string/
Share on other sites

It's ok, sprintf is confusing :)  That's normal.

 

Basically, ths %s and %d will be filled in by the other arguments to sprintf, in the order they appear.

 

The first mysql_real_escape_string() will go in the first %s, and the second one in the second %s

 

Then finally, $_POST['user_id'] will be converted from an integer to a string and placed in %d.  The general rule is you use %d for integers, %f for floating point numbers and %s for strings.  This can be confusing in PHP, since strings and integers and floats are often converted automatically.  sprintf() is based on a C function, where such conversions had to be done explicitly.

Thanks... I was feeling really dumb for awhile  :).  But I am beginning to grasp it now.

 

I am still a bit confused as to why this function even exists though... Unless there is some advantage to doing it this way, unknown to me, it seems as if it is just taking a simple thing and making it harder for no reason.  Wrong?

 

Oh, btw, why is the mysql_real_escape_string referring back the the database '$link'? I currently don't have it refferencing the database connection.  Is this needed for it to work properly?

 

Regards,

 

Brandon

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.