[英]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行的数据(在本例中为'someFieldName')(记住,行从0开始!)。
$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);
}
这是你的代码,使用它。 它被测试了。
$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>';
谢谢
你可以在没有循环的情况下完成。 只需使用fetch_all命令即可
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.