php 将 sql 查询作为数组返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3384292/
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
Return sql query as array
提问by HW1
I'm using jqueryui and its Autocomplete plugin. It use a json to extract items.
我正在使用 jqueryui 及其自动完成插件。它使用 json 来提取项目。
I want to modify it so that items will be extracted from my db.
我想修改它,以便从我的数据库中提取项目。
Here is how items should be :
这是项目应该如何:
$items = array(
"Great <em>Bittern</em>"=>"Botaurus stellaris",
"Great2 <em>Bittern</em>"=>"Botaurus stellaris 2"
);
How to make an sql query that extract data from a table and write it like the code above into the php file ?
如何进行从表中提取数据的 sql 查询并将其像上面的代码一样写入 php 文件?
Table : customer
id_customer | name_customer | country_customer
I want that array produce id_customer => name_customer
我想要那个数组产生 id_customer => name_customer
回答by Felix Kling
The query is just:
查询只是:
SELECT id_customer, name_customer FROM customer
and you can generate the array like so (assuming you are using MySQL):
并且您可以像这样生成数组(假设您使用的是 MySQL):
$items = array();
$result = mysql_query($sql);
while(($row = mysql_fetch_assoc($result))) {
$items[$row['id_customer']] = $row['name_customer'];
}
References:MySQL SELECTsyntax, mysql_query(), mysql_fetch_assoc()
回答by user408266
<?php
//Use mysql_connect for connect to a Db
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select a DB
$db_selected = mysql_select_db('db_name', $link);
if (!$db_selected) {
die ('Can\'t use dbame_n : ' . mysql_error());
}
//Build a query
$sql = "SELECT id_customer, name_customer FROM customer";
//Send de query to db
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// Initialize Array
$arr_customers = array();
while(($row = mysql_fetch_assoc($result))) {
$arr_customers[$row['id_customer']] = $row['name_customer'];
}
// convert to JSON
$json = json_encode($arr_customers);
// Send to JqueryUI
echo $json;
exit();
?>

