views:

63

answers:

2

Hello,

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

+1  A: 

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

Felix Kling
Doesn't work Felix.
HW1
Sorry sorry, it works, I just made an error. Thanks a lot :)
HW1
A: 
<?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();
    ?>
I wonder what would JqueryUI do with all these `'Could not connect: '` if happens
Col. Shrapnel