PHP - 基本选择查询仅返回mysql数据库的第一行

时间:2014-07-25 04:13:58

标签: php mysql sql

我一直在运行查询哦phpMyAdmin并显示所有行,但我在php中的查询只返回第一行。

$result = $mydb -> query("SELECT * FROM music_sheet WHERE category='".$_REQUEST["submitter"]."'"); 

print(count($result)); //always returns 1

for ($x = 0; $x < count($result); $x++) {
    $row = mysqli_fetch_row($result);
}

5 个答案:

答案 0 :(得分:2)

供参考,这是count()返回1的原因。 From the manual:

  

如果参数不是数组,或者不是具有已实现Countable接口的对象,则返回1。有一个例外,如果array_or_countable [参数]为NULL,则返回0。

由于$result是从您的查询返回的资源(对象),而不是您在循环中获取的数据,而是从资源中获取实际数据,{{ 1}}将返回count($resource)

您的解决方案当然是使用1。要从此资源中检索数据,您需要按原样循环,但要么使用mysqli_num_rows()代替mysqli_num_rows(),要么使用其他(更常见的)循环结果集的方式,例如这样:

count()

答案 1 :(得分:1)

您必须使用mysqli_num_rows($result)函数来计算MySQLi查询返回的行。

答案 2 :(得分:0)

试试这个

echo mysqli_num_rows($result);

答案 3 :(得分:0)

while($row = mysqli_fetch_row($result)) {
// write your code...
}

使用此代替for for循环

答案 4 :(得分:0)

查询方法返回给您的第一件事是资源/对象。此查询方法始终使用SELECT,SHOW,DESCRIBE或EXPLAIN查询返回mysqli_result对象以进行成功查询。对于其他成功的查询,mysqli_query()将返回TRUE。因此,它始终将其视为&#34; 1&#34;,您应该尝试的是:

$result = $mydb -> query("SELECT * FROM music_sheet WHERE category='".$_REQUEST["submitter"]."'"); 

$numRows = $result->num_rows;

print(count($numRows)); //it should show you the total amount of rows

//verify the amount of rows before of tryng to loop over it
if ($numRows) {
    while($object = mysqli_fetch_object($result)){
    //for each loop you will have an object with the attributes of the row
    echo $object->song_name; 
    }
}

这应该有效,

问候。