php 获取所有mysql选定的行到一个数组中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11264395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:07:46  来源:igfitidea点击:

Get all mysql selected rows into an array

phpmysqlarrays

提问by Gandalf

I am wondering if there a function in php that can allow me put all my selected data in an array .Currently i am using mysql_fetch_array and as i have read in the manual,that function won't fetch every record in the table.

我想知道 php 中是否有一个函数可以让我将所有选定的数据放入一个数组中。目前我正在使用 mysql_fetch_array 并且正如我在手册中所阅读的那样,该函数不会获取表中的每条记录。

$result = mysql_query("SELECT * FROM $tableName");            
$array = mysql_fetch_array($result);

  echo json_encode($array);

回答by Mike Mackintosh

I would suggest the use of MySQLi or MySQL PDO for performance and security purposes, but to answer the question:

为了性能和安全目的,我建议使用 MySQLi 或 MySQL PDO,但要回答这个问题:

while($row = mysql_fetch_assoc($result)){
     $json[] = $row;
}

echo json_encode($json);

If you switched to MySQLi you could do:

如果您切换到 MySQLi,您可以执行以下操作:

$query = "SELECT * FROM table";
$result = mysqli_query($db, $query);

$json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($json );

回答by John Conde

  1. Loop through the results and place each one in an array

  2. use mysqli_fetch_all()to get them all at one time

  1. 循环遍历结果并将每个结果放在一个数组中

  2. 用于mysqli_fetch_all()一次全部获取

回答by Brandon Ferrara

You could try:

你可以试试:

$rows = array();
while($row = mysql_fetch_array($result)){
  array_push($rows, $row);
}
echo json_encode($rows);

回答by dev4092

$name=array(); 
while($result=mysql_fetch_array($res)) {
    $name[]=array('Id'=>$result['id']); 
    // here you want to fetch all 
    // records from table like this. 
    // then you should get the array 
    // from all rows into one array 
}

回答by Dragooon

you can call mysql_fetch_array() for no_of_row time

您可以在 no_of_row 时间内调用 mysql_fetch_array()