0

I am using auto complete where the suggestions come from database and it is working fine, however I tried to change it to mysqli but it doesn't work. It doesn't show any suggestions;no error.

  1. what I am missing on the mysqli end?
  2. How can I be able to add more tables(I have like 40 tables)? Thanks.

MySQL:

 <?php
 mysql_connect("localhost","root","");
 mysql_select_db("database");

 $term=$_GET["term"];

 $query=mysql_query("SELECT * FROM products1 where title like '%".$term."%' order by id ");
 $json=array();

    while($student=mysql_fetch_array($query)){
         $json[]=array(
                    'value'=> $student["title"],
                    'label'=>$student["title"]
                        );
    }

 echo json_encode($json);

?> 

What I tried with MySQLi prepared statements:

<?php
$mydb = new mysqli('localhost', 'root', '', 'database');
$q = $_POST['term'];
$stmt = $mydb->prepare(" SELECT * from products1 where title LIKE ? ");
echo $mydb->error;
$stmt->bind_param('s', $q);
$stmt->execute();
?>
<?php
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$json[]=array(
            'value'=> $student["title"],
            'label'=>$student["title"]
                             );


}
echo json_encode($json);

?>
amdvb
  • 209
  • 1
  • 6
  • 15
  • You probably just need to put the `%` around the search term. `$q = '%'.$_POST['term'].'%';` http://stackoverflow.com/questions/15229880/mysqli-prepare-statement-error-when-used-for-like – Jonathan Kuhn Sep 13 '13 at 22:34

1 Answers1

0

First of all, Jonathan was right in suggesting to add wildcard('%') in the term. Your mistake was using the variable $student instead of $row (vice versa) in the loop.

<?php
$mydb = new mysqli('localhost', 'root', '', 'test');
$q = '%'.$_POST['term'].'%';
$stmt = $mydb->prepare(" SELECT * from products1 where title LIKE ? ");
echo $mydb->error;
$stmt->bind_param('s', $q);
$stmt->execute();


$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$json[]=array(
        'value'=> $row["title"],
        'label'=>$row["title"]
                         );
}
echo json_encode($json);

?>

P.S.: Make sure your query works first. And, the columns you use in the $row['columnName'] actually exists.

Gx.Zero
  • 407
  • 1
  • 4
  • 10
  • Lol. That worked for me. Take note of my query. I didn't use the same as yours. (I'll edit it. Looks like you just copy-pasted.) – Gx.Zero Sep 14 '13 at 08:02
  • the prob was actually using `$_POST` instead of `$_GET`. – amdvb Sep 14 '13 at 23:06