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
https://forums.phpfreaks.com/topic/90903-variable-in-select-statement/
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>";
}

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>"; 
      }

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.