-1

I'm selecting data from mysql database and print it in a webpage. I'm using wamp server. why I can't fetch the data ?

$result = mysql_query("SELECT userid FROM user WHERE logid = 'root'") or die(mysql_error());
echo $result; //result view as Resource id #7

but I count number of rows which equels to root it views as 1

$result = mysql_query("SELECT userid FROM user WHERE logid = 'root'") or die(mysql_error());
$no_of_rows = mysql_num_rows($result);
echo $no_of_rows; //result view as 1
AyB
  • 11,609
  • 4
  • 32
  • 47
Dumindu Madushanka
  • 494
  • 1
  • 9
  • 19
  • As an aside, the `mysql` extension is deprecated, you should move to PDO. Also, you do not need to quote a variable to echo it. See @ICanHasCheezburger answer. – Eamonn May 04 '14 at 10:44
  • There is a ticket already created about this issue: http://stackoverflow.com/questions/7519549/printing-result-of-mysql-query-from-variable – Rafayel A. May 04 '14 at 10:47
  • @Eamonn sorry. I have't use quote there. when I type here I was mistaken. – Dumindu Madushanka May 04 '14 at 10:47

2 Answers2

1

You use mysql_fetch_row() or mysql_fetch_assoc() (to retrieve by column name) as:

while($row=mysql_fetch_row($result)){
var_dump($row); 
#or echo $row[0]; echo $row[1]; etc. based on the number of columns returned
#if you used mysql_fetch_assoc, you retrieve by echo $row['column1']; etc.
}

$result is the result set and contains the the total rows returned from the table, use the above function mysql_fetch_row() to retrieve each row from it in a loop.

Note:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Community
  • 1
  • 1
AyB
  • 11,609
  • 4
  • 32
  • 47
0

Besides of you need to use PDO instead of Mysql, you could try to code your select queries like this:

<?php 

$sql = " 
    SELECT 
        userid
    FROM 
        user 
    WHERE
        logid = 'root'
"; 

if(!$res = mysql_query($sql)) 
{ 
    trigger_error(mysql_error().'<br />In query: '.$sql); 
} 
elseif(mysql_num_rows($res) == 0) 
{ 
    echo 'No results'; 
} 
else 
{ 
    while($row = mysql_fetch_assoc($res)) 
    { 
        echo $row[0].'<br />'; // Use 0 for the first column or the name of the column
    } 
} 
?>
R Pelzer
  • 1,188
  • 14
  • 34
  • _[It only returns an associative array](http://www.php.net/manual/en/function.mysql-fetch-assoc.php#refsect1-function.mysql-fetch-assoc-description)_. It should be `$row['column_name']` – AyB May 04 '14 at 10:55