1

I try results from db for autocomplete search. I use this code for getting names, in db I have a row with four columns that can contain the searched keyword.

function search_results($conn,$str){

$sql = "SELECT g_custom_1 as str FROM gallery WHERE  g_custom_1 LIKE '%{$str}%'";
$sql .= "SELECT g_custom_2 as str FROM gallery WHERE  g_custom_2 LIKE '%{$str}%'";
$sql .= "SELECT g_custom_3 as str FROM gallery WHERE  g_custom_3 LIKE '%{$str}%'";
$sql .= "SELECT g_custom_4 as str FROM gallery WHERE  g_custom_4 LIKE '%{$str}%'";


//$sub_data=array();
if (mysqli_multi_query($conn,$sql))
{
    $data=array();
    do
    {
        // Store first result set
        if ($result=mysqli_store_result($conn)) {
        // Fetch one and one row
        while ($row=mysqli_fetch_row($result))
        {
            $data[]=$row['str'];
        }
        // Free result set
        mysqli_free_result($result);
        }
    }
    while (mysqli_next_result($conn));
}
else{
    echo "error";
}
$data_unique=array_unique($data);
return $data_unique;
   }

1 Answers1

0

You need to separate each query using a semicolon. Here is your current string:

$sql="SELECT g_custom_1 as str FROM gallery WHERE  g_custom_1 LIKE '%{$str}%'SELECT g_custom_2 as str FROM gallery WHERE  g_custom_2 LIKE '%{$str}%'SELECT g_custom_3 as str FROM gallery WHERE  g_custom_3 LIKE '%{$str}%'SELECT g_custom_4 as str FROM gallery WHERE  g_custom_4 LIKE '%{$str}%'";

Notice how the SELECT in the subsequent queries are smashed into the rear end of the previous query?

I might suggest:

$sql[]="SELECT g_custom_1 as str FROM gallery WHERE  g_custom_1 LIKE '%{$str}%'";
$sql[]="SELECT g_custom_2 as str FROM gallery WHERE  g_custom_2 LIKE '%{$str}%'";
$sql[]="SELECT g_custom_3 as str FROM gallery WHERE  g_custom_3 LIKE '%{$str}%'";
$sql[]="SELECT g_custom_4 as str FROM gallery WHERE  g_custom_4 LIKE '%{$str}%'";
if(mysqli_multi_query($conn,implode(';',$sql))){

You might also find this answer informative: Strict Standards: mysqli_next_result() error with mysqli_multi_query

Community
  • 1
  • 1
mickmackusa
  • 43,625
  • 12
  • 83
  • 136