Jump to content

Sprintf quesion


graham23s

Recommended Posts

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

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

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

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

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.