将sql查询作为数组返回

问题描述:

I'm using jqueryui and its Autocomplete plugin. It use a json to extract items.

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 ?

Table : customer
id_customer | name_customer | country_customer

I want that array produce id_customer => name_customer

我正在使用jqueryui及其Autocomplete插件。 它使用json来提取项目。 p>

我想修改它以便从我的数据库中提取项目。 p>

以下是项目应该如何 be: p>

  $ items = array(
“Great&lt; em&gt; Bittern&lt; / em&gt;”=&gt;“Botaurus stellaris”,
“Great2&lt; em&gt;  ; Bittern&lt; / em&gt;“=&gt;”Botaurus stellaris 2“
); 
  code>  pre> 
 
 

如何进行从表中提取数据并写入的SQL查询 它像上面的代码一样进入php文件? p>

 表:customer 
id_customer |  name_customer |  country_customer 
  code>  pre> 
 
 

我希望该数组产生 id_customer =&gt; name_customer code> p> div>

The query is just:

SELECT id_customer, name_customer FROM customer

and you can generate the array like so (assuming you are using MySQL):

$items = array();

$result = mysql_query($sql);
while(($row = mysql_fetch_assoc($result))) {
    $items[$row['id_customer']] = $row['name_customer'];
}

References: MySQL SELECT syntax, mysql_query(), mysql_fetch_assoc()

<?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();
    ?>