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
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.
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.
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
}
}
?>