notepad Posted May 4, 2007 Share Posted May 4, 2007 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? Quote Link to comment Share on other sites More sharing options...
btherl Posted May 4, 2007 Share Posted May 4, 2007 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. Quote Link to comment Share on other sites More sharing options...
notepad Posted May 4, 2007 Author Share Posted May 4, 2007 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 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.