2

I got this PHP code:

// connect to mysql
require_once('includes/connect.php');
// include config
include('includes/config.php');

$nameser = $_GET['term'];

$search = Array();
$names = '';
$result = mysql_query("SELECT name FROM customers WHERE name LIKE '%".$nameser."%'");
while ($row = mysql_fetch_assoc($result))
    $names = json_encode($row['name']);

echo $names;

But the output is not formatted right, so the autocomplete script cannot figure out what it should do with it.

Also, this example only outputs 1 entry, but there should be far more than that.

Any ideas?

Frederik
  • 632
  • 4
  • 16
  • 34

1 Answers1

5

Here is the correct code:

$names = array();
while ($row = mysql_fetch_assoc($result))
  $names[] = $row['name'];

echo json_encode($names);

And as mysql_* functions are deprecated, consider using mysqli or PDO.

flowfree
  • 16,356
  • 12
  • 52
  • 76
  • It doesn't work quite as expected - I get some of the output correct, but some of results just show up as null. – Frederik Jun 17 '12 at 09:15
  • Also - how much of a job would it be to rewrite it to use mysqli? – Frederik Jun 17 '12 at 09:15
  • For the `NULL`, I don't know for sure about the problem. Perhaps some of the values in `customer.name` are `NULL`? Converting your code from `mysql_*` to `mysqli` should not be too difficult. – flowfree Jun 17 '12 at 09:18
  • Doing the query in phpmyadmin returns no rows with the value NULL - they do however contain special danish characters (Æ,Ø,Å) – Frederik Jun 17 '12 at 09:40
  • Alright, fixed that part with a htmlentities. Now I just got the problem that in my search box, Ø for example shows up as Ø and not Ø. – Frederik Jun 17 '12 at 09:59
  • any idea about my last comment? – Frederik Jun 17 '12 at 11:22
  • I think you should remove the `htmlentities` and add this meta tag `` in your HTML. – flowfree Jun 17 '12 at 12:01
  • I actually got it fixed with help from [link](http://stackoverflow.com/questions/3488016/using-html-in-jquery-ui-autocomplete) – Frederik Jun 17 '12 at 12:37