[英]why select * from return only the first field?
我正在对db进行下一个查询
$result = $con->query ( 'select * from table');
$datos = $result->fetch_assoc();
echo "Cantidad de datos: ".count($datos).",";
print_r($datos);
应显示包含所有条目的数组,但仅显示第一个条目。 为什么?
PS:我看过其他帖子,但我没有限制或加入。
fetch_assoc将结果行作为关联数组提取
所以你可以通过while循环遍历所有行,如果可能的话,可以获取另一行。
$count = 0;
while( $row = $result->fetch_assoc() ){
// You can access data like this -->> $row['data'];
$count++;
}
echo $count;
完成后,你应该释放与结果相关的记忆
$result->free();
但是,如果您只想获得计数,可以使用mysql_num_rows返回结果集中的行数。
$count = mysql_num_rows($result);
echo $count;
当你执行$datos = $result->fetch_assoc();
时, fetch_assoc
只返回一行$datos = $result->fetch_assoc();
你可以在PDO
和mysqli
获取整个数组。这是一个使用mysqli-> fetch_all函数获取所有行的示例 ,希望这有帮助!
//Database Connection
$sqlConn = new mysqli($hostname, $username, $password, $database);
//Build SQL String
$sqlString = "SELECT * FROM my_table";
//Execute the query and put data into a result
$result = $this->sqlConn->query($sqlString);
//Copy result into a associative array
$resultArray = $result->fetch_all(MYSQLI_ASSOC);
//Copy result into a numeric array
$resultArray = $result->fetch_all(MYSQLI_NUM);
//Copy result into both a associative and numeric array
$resultArray = $result->fetch_all(MYSQLI_BOTH);
请始终参考您正在使用的框架手册。 fetch_assoc();获取结果行作为关联数组。 如果要获取所有行,请使用while语句,如下所示:
$result = $c->query('SELECT user,host FROM mysql.user');
while ($row = $result->fetch_assoc()) {
printf("'%s'@'%s'\n", $row['user'], $row['host']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.