简体   繁体   English

num_rows和count()不匹配-PHP

[英]num_rows and count() mismatch - php

$result = $conn->query($sql);
echo $result->num_rows; //2 is value produced

BUT

$tagResult =  mysqli_fetch_array($result,MYSQLI_NUM);
echo count($tagResult); //1 is the value produced

Isn't it suppose to produce the same number of values? 是不是应该产生相同数量的值?

mysqli_fetch_array() mysqli_fetch_array()

Returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset. 返回与获取的行对应的字符串数组;如果结果集中没有更多的行,则返回NULL。

So it only fetches 1 row. 因此,它仅获取1行。 To get both/all you need to fetch all rows in a loop: 要同时获取两者/全部,您需要循环获取所有行:

while($tagResult[] =  mysqli_fetch_array($result,MYSQLI_NUM)) {}
echo count($tagResult);

mysqli_fetch_array will fetch one row at a time, wherever the pointer for the result currently is. mysqli_fetch_array将一次获取一行,无论当前结果的指针在哪里。 When you first get the result, the pointer is at the first row. 首次获得结果时,指针位于第一行。 When you call mysqli_fetch_array, it will grab record 1 (where the pointer is) then increment the pointer to the next record. 当您调用mysqli_fetch_array时,它将获取记录1(指针所在的位置),然后将指针增加到下一条记录。 When you call it again, it will grab record 2, and so on. 再次调用它时,它将获取记录2,依此类推。

If you have more than one row returned, you will need to loop through the results, calling mysqli_fetch_array on each row. 如果返回的行多,则需要遍历结果,在每一行上调用mysqli_fetch_array。 Because mysqli_fetch_array returns null when there are no more rows, you can use a simple while loop: 因为当没有更多行时mysqli_fetch_array返回null,所以可以使用一个简单的while循环:

$result = $conn->query($sql);
echo $result->num_rows; //2 is value produced

$count = 0;
while ($tagResult = mysqli_fetch_array($result,MYSQLI_NUM))
{
    print_r($tagResult); // Output each row
    $count ++;
}
echo $count; //outputs 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM