4

I am planning to use jQuery UI Autosuggest for a search form. So I need a json output which can be used by jQuery UI Auto suggest.

Here's the database alt text

Table name recent_tags

I have tried this

First connect to db

$do = mysql_query("SELECT * FROM recent_tags where query like '%" . $_GET['query'] . "%'"); 

while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
    $row_array['query'] = $row['query'];
    array_push($return_arr,$row_array);
}

echo json_encode($return_arr);

but It's not working..

Please guide me..

EDIT :

getting error

Warning: array_push() [function.array-push]: First argument should be an array in /pathto/my/file.php

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vamsi Krishna B
  • 11,377
  • 15
  • 68
  • 94

2 Answers2

6

Try this:

$return_arr = Array();

$query = mysql_real_escape_string($_GET['query']);
$result = mysql_query("SELECT * FROM recent_tags where query like '%" . $query . "%'"); 

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    array_push($return_arr,$row);
}

echo json_encode($return_arr);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Charles Hooper
  • 2,739
  • 1
  • 19
  • 16
3

Probably not the route you will go but I'll give this answer for completeness or just because I find it interesting:

There is also the possibility to let the database generate the JSON for you. mysqludf.org have a set of MYSQL user defined functions for JSON available here. Below is an example of converting a few fields to JSON:

select json_array(
   customer_id
   ,first_name
   ,last_name
   ,last_update
   ) as customer
from   customer 
where  customer_id =1;

If you have a lot of data to convert this may perhaps prove to be more scalable.

Hannes de Jager
  • 2,903
  • 6
  • 37
  • 57
  • Probably not more scalable to do this in the database, IMHO, because web frontends are (in general) easier to scale than relational databases. – Charles Hooper Dec 24 '12 at 22:05
  • link is dead. do you know of a mirror or alternative? Otherwise, just delete the answer please. – Gordon Jul 30 '13 at 11:53