I've been running the query oh phpMyAdmin and it shows all the rows, but my query in php only returns the first row.
$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);
}
For reference, here's why count()
is returning 1
. From the manual:
If the parameter is not an array or not an object with implemented Countable interface, 1 will be returned. There is one exception, if array_or_countable [ the parameter ] is NULL, 0 will be returned.
Since $result
is a resource (object) that is returned from your query, not an array which you would get within your loop getting the actual data out of the resource, count($resource)
will return 1
.
Your solution is of course to use mysqli_num_rows()
. To retrieve data from this resource, you need to loop over it as you are doing, but either use mysqli_num_rows()
in place of count()
, or other (more common) ways of looping through a result set, like so:
while($row = mysqli_fetch_row($result)) {
// do stuff
}
您必须使用mysqli_num_rows($result)
函数对MySQLi查询返回的行进行计数。
尝试这个
echo mysqli_num_rows($result);
while($row = mysqli_fetch_row($result)) {
// write your code...
}
Use this instead of the for loop
the first thing that the query method returns to you is a resource/object. This query method always return a mysqli_result object for successful queries using SELECT, SHOW, DESCRIBE or EXPLAIN queries . For other successful queries mysqli_query() will return TRUE. For that reason it always count it as "1", what you should try is:
$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;
}
}
This should work,
Regards.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.