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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.