2

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

4
  • To give you the exact code, we would need to know what your database schemas looks like. What are your field names? Commented Aug 2, 2010 at 0:28
  • It seems that i made an error with posting a new message in place of a comment. Anyway, message above edited (thanks for admin by the way :) ) Commented Aug 2, 2010 at 0:45
  • Do your id's have HTML formatting (<em>) on them? You shouldn't have that on that DB. Commented Aug 2, 2010 at 0:52
  • No, it's just an exemple extracted from the jquerui docs. Commented Aug 2, 2010 at 1:04

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I wonder what would JqueryUI do with all these 'Could not connect: ' if happens

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.