Jump to content

Variable in SELECT statement


Siggles

Recommended Posts

Hi, this one should be simple...

 

  $hello = 2;

  $results = mysql_query('SELECT username FROM `users` WHERE `user_id`="$hello"');

  while($row = mysql_fetch_array($results)){

            echo "<td>$row[username]</td>"; }

 

Any ideas why the variable does not go in to the SELECT statement. If I change the variable for a number I get a result. Does it need to be global or something?

 

Link to comment
Share on other sites

You don't need the single quotes on the names of tables or on column headings, only on values. Also, rather than telling it to echo $row[username], first extract the data from the array and then just echo $username. To take both these into account, your new code would look like this:

 

$hello = 2;
$results = mysql_query("SELECT username FROM users WHERE user_id='$hello'");
while($row = mysql_fetch_array($results)) {
     extract($row);
     echo "<td>$username</td>";
}

Link to comment
Share on other sites

Hi, this one should be simple...

 

  $hello = 2;

  $results = mysql_query('SELECT username FROM `users` WHERE `user_id`="$hello"');

  while($row = mysql_fetch_array($results)){

            echo "<td>$row[username]</td>"; }

 

Any ideas why the variable does not go in to the SELECT statement. If I change the variable for a number I get a result. Does it need to be global or something?

 

 

The only thing wrong with the query string is your use of quotes. Use outer double quotes and single quotes round '$hello'.  (Actually, as $hello is numeric, the quotes around it are unnecessary. Only string values need quotes otherwise they will be interpreted as column names)

 

$x = 123;

echo "$x";  // --> 123
echo '$x';  //  --> $x

 

When using arrays with strings as keys, the index should be quoted ie $row['username'], NOT $row[username]

 

So

 

<?php
     $hello = 2;
     $results = mysql_query("SELECT username FROM `users` WHERE `user_id`= $hello");
     while($row = mysql_fetch_array($results)) {
             echo "<td>{$row['username']}</td>"; 
      }

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.