如何使用php中的自动完成功能在标签中显示两个数据库值中的任何一个

时间:2016-07-25 06:29:38

标签: php autocomplete label

这是我的以下代码:

<?php include("config.php");
include("session-user.php");

$term = trim(strip_tags($_GET['term']));//retrieve the search term that    autocomplete sends

$qstring = "SELECT product_title, product_details, product_id  FROM tbl_product WHERE product_title LIKE '".$term."%' OR product_details LIKE '".$term."' and is_delete = '0'";
$result = mysqli_query($con,$qstring);//query the database for entries containing the term

while ($row = mysqli_fetch_array($result))//loop through the retrieved values
{
    $row['label']=htmlentities($row['product_title']);
    $row['label']=htmlentities($row['product_details']);
    $row['product_id']=htmlentities($row['product_id']);
    $row_set[] = $row;//build an array
}
echo json_encode($row_set);

目前它只显示labels中的一个,我想用两个标签中的任何一个进行搜索

我怎样才能实现它?

2 个答案:

答案 0 :(得分:2)

此代码存在问题: -

 $row['label']=htmlentities($row['product_title']);
 $row['label']=htmlentities($row['product_details']);

由于相同的索引(label),它首先覆盖了第一个,使用如下: -

 $row['label']=htmlentities($row['product_title']);
 $row['label1']=htmlentities($row['product_details']); 

检查我已将第二个索引更改为label1

自动完成工作,每个值使用一个标签,以便您可以将它们连接起来(label-label1)并显示。

可能会对您有所帮助: -

while ($row = mysqli_fetch_array($result))//loop through the retrieved values
{
    if($row['product_title'] !=='' && $row['product_details'] ==''){ // if product_title is present but  product_details is not present
      $row['label']=htmlentities($row['product_title']);
      $row['product_id']=htmlentities($row['product_id']);
      $row_set[] = $row;//build an array
    }else if($row['product_details'] !=='' && $row['product_title'] ==''){ // if product_details is present but  product_title is not present
      $row['label']=htmlentities($row['product_details']);
      $row['product_id']=htmlentities($row['product_id']);
      $row_set[] = $row;//build an array
    }else if($row['product_details'] !=='' && $row['product_title'] !==''){ // if both are present
      $row['label']=htmlentities($row['product_title']);
      $row['product_id']=htmlentities($row['product_id']);
      $row_set[] = $row;//build an array
    } 
}

注意: - 在上面的代码中,如果两个值(product_titleproduct_title)都存在,那么product_title将显示为标签,否则相应的值将显示为标签。

答案 1 :(得分:1)

试试这个

    $row['label1']=htmlentities($row['product_title']);
    $row['label2']=htmlentities($row['product_details']);

并将查询更改为

$qstring = "SELECT product_title, product_details, product_id  FROM tbl_product WHERE product_title LIKE '".$term."%' OR product_details LIKE '".$term."%' and is_delete = '0'";