mysqli union安排每个talbe的结果

时间:2015-09-05 22:57:02

标签: php mysqli

我使用mysqli union搜索数据库,如下所示:

$search = security($_POST['search']);
$search_val = "%{$search}%";
$search_disp = '';

if($searchQ = $db->prepare(
    "(SELECT name AS `name1` FROM `table1` WHERE name LIKE ? LIMIT 8)
    UNION 
     (SELECT heading AS `name2` FROM `table2` WHERE heading LIKE ? LIMIT 8)
    ")){
        if($searchQ->bind_param("ss",$search_val,$search_val)){
            if($searchQ->execute()){
               $searchQ->store_result();

               if($searchQ->num_rows){
                  $searchQ->bind_result($search_result);
                  while($searchQ->fetch()){
                      $search_disp.='
                          <div>'.$search_result.'</div>
                      ';
                  } 
               }
            }
            else{echo '$db->error' exit();}
        }
        else{echo '$db->error' exit();}
    }
    else{echo '$db->error' exit();}

    echo $search_disp; exit();

我不知道如何实现根据它来自的表格显示不同的结果,因为我将两个结果作为相同的varialbe($ search_result)获取,例如:

if(result from table one){
    $search_disp.='
        <div class="talbe1">'.$search_result.'</div>
    ';
}
else if(result from table two){
    $search_disp.='
        <div class="talbe2">'.$search_result.'</div>
    ';
}

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:3)

您可以向结果集添加其他行tbl,然后使用它:

(SELECT 'table1' as tbl, name FROM `table1` WHERE name LIKE ? LIMIT 8)
UNION 
(SELECT 'table2' as tbl, heading AS name FROM `table2` WHERE heading LIKE ? LIMIT 8)