views:

28

answers:

6

Newish to mysql. I have a query and it is not showing the value of the cell just the row name:

$sql="SELECT 'first' from `users` WHERE `id`= $userid ";
$res=mysql_query($sql) or die(mysql_error());

$row=mysql_fetch_assoc($res); 

echo $row['first'] ; 

What am I doing wrong????

A: 

Try:

echo $row[0]['first'];
Leon
A: 

First remove quotes from 'first' - it is a column so don't put it in quotes, you can use ` istead. Next loop through results and that's all.

$sql="SELECT first from `users` WHERE `id`= $userid ";
$res=mysql_query($sql) or die(mysql_error());

while($row=mysql_fetch_assoc($res))
  echo $row['first'] ; 
tuffkid
+1  A: 

Brackets in your query is wrong:

$sql = "SELECT 'first' from `users` WHERE `id` = $userid";

Must be:

$sql = "SELECT `first` from `users` WHERE `id` = $userid";

Note difference in first

Otar
A: 
SELECT 'first' 

will simply return the string first.

remove the quotes.

youssef azari
A: 

like tuffkid said, however when an array is returned i preffer to use foreach instead of while. Also check if any result was returned before looping through the rows.

$row=mysql_fetch_assoc($res); 

if(mysql_num_rows($res) > 0):
    foreach($row as $r):
        echo $r['first'];
    endforeach;
else:
    echo"nothing found";
endif;
krike
A: 

$sql="SELECT 'first' from users WHERE id= $userid ";

you are using normal quotes to select instead of backticks you are not selecting anything from the database.

use $sql="SELECT first from users WHERE id= $userid "; instead

and side note: never "be sure" that your query returns exactly 1 row

use mysql_fetch_assoc() in a loop and check if you really retrieve 1 result.

kali