从mysql表中获取行到php数组


Get rows from mysql table to php arrays

我怎么能得到mysql表的每一行,并把它放在一个php数组?我需要一个多维数组吗?这样做的目的是为了以后在谷歌地图上显示一些点。

需要从表中获取所需的所有数据。这样就可以了:

$SQLCommand = "SELECT someFieldName FROM yourTableName";

这一行进入到表中,并从表中获取'someFieldName'中的数据。如果您想获得多个列,可以在'someFieldName'中添加多个字段名。

$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data

$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
     $yourArray[$index] = $row;
     $index++;
}

上面的循环遍历每一行,并将其作为元素存储在您创建的新数组中。然后你可以对这个信息做任何你想做的事情,比如打印到屏幕上:

echo $row[theRowYouWant][someFieldName];

因此,如果$theRowYouWant等于4,它将是第5行(记住,行从0开始!)的数据(在本例中为'someFieldName')。

$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
   $array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.

其他答案确实有效-然而OP要求所有行,如果所有字段都需要,那么最好将其保留为通用而不是在数据库更改时更新php

$query="SELECT * FROM table_name";

在这一点上,返回的数据也可以是通用的——我真的很喜欢JSON格式,因为它可以动态更新,并且可以很容易地从任何源提取。

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) 
{
  echo json_encode($row);
}

您可以不使用循环。只需使用fetch_all命令

$sql     = 'SELECT someFieldName FROM yourTableName';
$result  = $db->query($sql);
$allRows = $result->fetch_all();

这是你的代码,使用它。

$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY 
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC)) 
{
    array_push($data_array,$row);
}

mysql_free_result($queryResult);

//TEST TO SEE THE RESULT OF THE ARRAY 
echo '<pre>';
print_r($data_array);
echo '</pre>';