英文:
return mysql_fetch_assoc results as an array
问题
我试图从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: " . $conn->connect_error);
}
$query = "SELECT name FROM options WHERE page='$table' AND type='view' AND value='1'";
$result = $conn->query($query);
$options = array();
while($row = $result->fetch_assoc()) {
$options[] = $row['name'];
}
$conn->close();
return $options;
}
$options = get_view_options($page);
这里是我希望你能获得的结果:
Array ( [0] => location [1] => owner [2] => id )
如何实现这个目标的任何建议都将不胜感激。
英文:
I am trying to retreive results from a mysql query as an array. Here is a sample of the code :
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);
Here is the result I get from print_r ($options);
:
Array ( [name] => location )
Here is what I was hoping to get :
Array ( [0] => location [1] => owner [2] => id )
Any suggestion on how I can achieve this would be much appreciated.
答案1
得分: 0
感谢 @aynber!以下是使用 fetch_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);
?>
输出为:Array ( [0] => location [1] => owner [2] => id )
英文:
Thanks @aynber!
Here is the final code with fetch_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);
?>
Which outputs : Array ( [0] => location [1] => owner [2] => id )
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论