graham23s Posted March 8, 2008 Share Posted March 8, 2008 Hi Guys, i'm seeing more and more examples with sprintf in the mysql query like: $user = "username_here"; $sql = sprintf("SELECT user FROM users WHERE user=%s",$user); $query = mysql_query($link,$sql); $num_username = mysql_num_rows($query); if($num_username > 0) { echo "That username is already taken."; } else { do_whatever } i don't fully understand how it works, like what is the %s for, and is there any advantages to using it or are you better off doing queries normally. thanks for any advice guys Graham Link to comment https://forums.phpfreaks.com/topic/95002-sprintf-quesion/ Share on other sites More sharing options...
btherl Posted March 8, 2008 Share Posted March 8, 2008 It's a matter of preference. Some people like sprintf style, others like "substitution" style. These are equivalent: $sql = sprintf("SELECT user FROM users WHERE user='%s' AND number='%s'",$user, $number); $sql = "SELECT user FROM users WHERE user='$user' AND number='$number'"; Link to comment https://forums.phpfreaks.com/topic/95002-sprintf-quesion/#findComment-486650 Share on other sites More sharing options...
Barand Posted March 8, 2008 Share Posted March 8, 2008 www.php.net/sprintf %s is a placeholder for a string argument %d is a placeholder for an integer argument etc You'll find that most of the queries like that are those generated by Dreamweaver. It is useful for other things <?php printf ('#%02X%02X%02X ', 255, 8, 200); // #FF08C8 printf ('%06d', 42); // 000042 ?> Link to comment https://forums.phpfreaks.com/topic/95002-sprintf-quesion/#findComment-486651 Share on other sites More sharing options...
graham23s Posted March 8, 2008 Author Share Posted March 8, 2008 ah so its a total preference thing, thanks you guys its cleared it up for me. Graham Link to comment https://forums.phpfreaks.com/topic/95002-sprintf-quesion/#findComment-486840 Share on other sites More sharing options...
thebadbad Posted March 8, 2008 Share Posted March 8, 2008 It's often used when you want to run mysql_real_escape_string on some database inputs: example from the manual: <?php $query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'", mysql_real_escape_string($user), mysql_real_escape_string($password)); ?> Link to comment https://forums.phpfreaks.com/topic/95002-sprintf-quesion/#findComment-486849 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.