开发者

Return sql query as array

I'm using jqueryui and its Autocomplete p开发者_开发百科lugin. 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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜