php多个选择2个表中的查询

时间:2017-09-22 13:57:57

标签: php mysql union

我有这个PHP代码,我有3个表,我想搜索所有这些

if(isset($_POST['search']))
    {
    $valueToSearch = $_POST['valueToSearch'];
    $query = "SELECT * FROM tbl_cloth_eng 
              UNION SELECT * FROM `tbl_cloth_gbc` 
              UNION SELECT * FROM `tbl_cloth_pcv`
              WHERE CONCAT(`supplier_prefix`, `supplier_name`, `stock_id`, `category`, `description`, `yield`, `size`, `color`, `usage_type`, `remarks`) 
              LIKE '%".$valueToSearch."%'";
    $search_result = filterTable($query);
    }
else 
    {
        $query = "SELECT * FROM `tbl_cloth_eng` UNION SELECT * FROM `tbl_cloth_gbc` UNION SELECT * FROM `tbl_cloth_pcv`";
        $search_result = filterTable($query);
    }

function filterTable($query)
    {
        $conn = mysqli_connect("localhost", "root", "", "redanura1");
        $filter_result = mysqli_query($conn, $query);
        return $filter_result;
    }

请帮我这个,它继续显示前2个表格中没有过滤的数据

1 个答案:

答案 0 :(得分:0)

UNION加入之前的查询结果,每个where都需要select。您还应该参数化此查询并查看使用全文索引。所以:

$query = "SELECT * FROM tbl_cloth_eng WHERE CONCAT(`supplier_prefix`, `supplier_name`, `stock_id`, `category`, `description`, `yield`, `size`, `color`, `usage_type`, `remarks`) 
          LIKE concat('%', ?, '%')
          UNION SELECT * FROM `tbl_cloth_gbc` WHERE CONCAT(`supplier_prefix`, `supplier_name`, `stock_id`, `category`, `description`, `yield`, `size`, `color`, `usage_type`, `remarks`) 
          LIKE concat('%', ?, '%') 
          UNION SELECT * FROM `tbl_cloth_pcv`
          WHERE CONCAT(`supplier_prefix`, `supplier_name`, `stock_id`, `category`, `description`, `yield`, `size`, `color`, `usage_type`, `remarks`) 
          LIKE concat('%', ?, '%');

然后绑定$valueToSearch 3次。