Php 以数组形式返回mysql_fetch_assoc结果
我试图以数组的形式检索mysql查询的结果。以下是代码示例:Php 以数组形式返回mysql_fetch_assoc结果,php,mysql,arrays,Php,Mysql,Arrays,我试图以数组的形式检索mysql查询的结果。以下是代码示例: function get_view_options($table) { include('config.php'); $conn = new mysqli($sql['host'],$sql['username'],$sql['password'],$sql['database']); if ($conn->connect_error){ die("Connection failed: "
function get_view_options($table) {
include('config.php');
$conn = new mysqli($sql['host'],$sql['username'],$sql['password'],$sql['database']);
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT name FROM options WHERE page='".$table."' AND type='view' AND value='1'";
$options = $conn->query($query)->fetch_assoc();
$conn->close();
return $options;
}
$options = get_view_options($page);
这是我从print\r($options)得到的结果代码>:
数组([name]=>位置)
以下是我希望得到的:
数组([0]=>位置[1]=>所有者[2]=>id)
任何关于我如何实现这一目标的建议都将不胜感激。谢谢@aynber!
下面是fetch_all()的最终代码
不确定您请求的数据来自何处,但请尝试选择*
从表中选择所有数据,并获取行()
而不是获取联索()
以获得数字索引行。所有者、id是什么?这些是字段?我猜你想要3行,而不是一行。改为使用,它将返回所有结果。使用fetch_all()获取所有结果,或者使用循环持续fetch_assoc()
,直到所有行用完。你可以在网上找到很多关于如何使用mysqli正确获取结果的例子,我有点惊讶我们需要在这里重复。你必须为这种类型的结构创建一个新的数组。您可以将while循环与fetch\u assoc一起使用,也可以将foreach与fetch\u all一起使用。
<?php
function get_view_options($table) {
include('config.php');
$conn = new mysqli($sql['host'],$sql['username'],$sql['password'],$sql['database']);
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT name FROM options WHERE page='".$table."' AND type='view' AND value='1'";
$options = $conn->query($query)->fetch_all();//changed from fetch_assoc()
$conn->close();
return $options;
}
//We create an array with all the results
$options = array();
foreach(get_view_options($page) as $option){
array_push($options,$option[0]);
}
print_r ($options);
?>