Click to See Complete Forum and Search --> : [RESOLVED] mysql_real_escape_string question


Kyleva2204
08-06-2008, 12:20 PM
When using this, do you have use use sprintf? IE:

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']);


or is it also safe to do this:


$sql = "INSERT INTO products (`name`, `description`, `user_id`) VALUES ('".mysql_real_escape_string($product_name, $link)."', '".mysql_real_escape_string($prodcut_description, $link)."', ".$_POST['user_id'].");";


I would assume both would be appropriate.. But I have been proven wrong before ^_^

thanks
Kyle

NogDog
08-06-2008, 01:27 PM
You could use either; just use whichever one you find easier to read and maintain. Or move up to the MySQLi extension and use prepared statements and bound variables, which can remove the need to call a separate escape function. :)

Kyleva2204
08-06-2008, 01:32 PM
Thanks :)

MrCoder
08-07-2008, 12:22 AM
$_POST['user_id'] should be typecast as an integer.
Also had a typo in "prodcut" and no need for the $link unless you are using more then one database connection simultaneously.


$sql = "INSERT INTO products (
`name`,
`description`,
`user_id`
) VALUES (
'".mysql_real_escape_string($product_name)."',
'".mysql_real_escape_string($product_description)."',
'".(int)$_POST['user_id']."'
)";