PHP选择mysql数据视图作为数字

时间:2014-05-04 10:39:49

标签: php mysql

我从mysql数据库中选择数据并将其打印在网页中。我正在使用wamp服务器。为什么我无法获取数据?

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

但是我计算等于根视图的行数为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

2 个答案:

答案 0 :(得分:1)

您使用 mysql_fetch_row() mysql_fetch_assoc()(按列名检索):

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是结果集,包含从表中返回的总行数,使用上面的函数mysql_fetch_row()从循环中检索每一行。

注意:

Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial

答案 1 :(得分:0)

除了你需要使用PDO而不是Mysql之外,你可以试着像这样编写你的选择查询:

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