2个表的动态搜索选项

时间:2013-11-28 08:56:42

标签: php mysql

这是我的问题,我在这里涉及2个表:TINVOICES和TJOBS

TINVOICES - Job_no
TINVOICES - Year
TJOBS - Staff
TINVOICES - Month
TJOBS - Country
TINVOICES - Paid
TJOBS - Client_no
TINVOICES - 30 Days

我希望搜索选项是动态的,就像它应该接受搜索工作和年份一样。或只支付或仅支付一个月......等等。我有两张桌子。 你能帮我解决一下我的方法吗?

请参阅下面的代码。

非常感谢你!

这是我的搜索选项:

Search Options


 if (isset($_POST['job_no'])) {
        $job_no = $_POST['job_no'];
        if ($_POST['job_no'] != "") { $job_no = " job_no=".$job_no." AND"; $search += 1;}
    }
    ..other ifs

if ($search != 0) {
    if (isset($_POST['country'])) {
        if ($_POST['country'] == "") {
            $query = "WHERE $job_no$month$id$year$staff_no$paid";
        }
        else {
            $query = "AND $job_no$month$id$year$staff_no$paid";
        }
    }
    else{
        $query = "WHERE $job_no$month$id$year$staff_no$paid";
    }
}                                       

//Remove string AND on the end of a query if found
if (substr($query, -3) == "AND") { $query = substr($query, 0, -3); } 

if (isset($_POST['country']) && $_POST['country'] != "") {      
    $country = $_POST['country'];
    if ($country == "All") {
        $sql = "SELECT p . * FROM tinvoices $query AS p ";
    }
    else if ($country == "Middle East") {
        $sql = "
        SELECT p . *
        FROM tinvoices AS p 
        LEFT JOIN tjobs AS j 
        ON p.job_no = j.job_no 
        WHERE j.location =  'Qatar' OR j.location = 'UAE' $query ";
    }
    else {
        $sql = "
        SELECT p . *
        FROM tinvoices AS p
        LEFT JOIN tjobs AS j
        ON p.job_no = j.job_no
        WHERE j.location =  '$country' $query ";
    }
    $result = mysqli_query($con,$sql) or die("MySQL Error: ".mysql_error());
}
elseif (isset($_POST['client_no']) && $_POST['client_no'] != "") {      
    $client_no = $_POST['client_no'];
    $sql = "
        SELECT p . *
        FROM tinvoices AS p
        LEFT JOIN tjobs AS j
        ON p.job_no = j.job_no
        WHERE j.location =  '$country' $query ";
    echo $sql;
}
else {
    $sql = "SELECT p . * FROM tinvoices AS p $query";
    //echo $sql;
    $result = mysqli_query($con,$sql) or die("MySQL Error: ".mysql_error());
}

1 个答案:

答案 0 :(得分:3)

要使搜索动态化,首先要确保表单元素名称与数据库表字段中的完全相同。对于两个表,可以在表单元素名称前加上tablename,然后是field。例如

  

如果您的数据库字段名称是tinvoices表中的位置,则您的位置元素名称应为tinvoices_location

因此,当提交表单时,您可以像这样循环遍历发布的数据 假设您有两个表table1和table2

    $sql = "SELECT table1.*, table2.* FROM table1 INNER JOIN table2 ON table2.id = table1.table2_column WHERE ";

$conditions = array();
    foreach($_POST as $key => $value){
    $tableFields = explode('_', $key);
    $conditions[] = $tableFields[0].'.'.$tableFields[1].' = "'.$value.'"';   // will produce table1.location = "Qatar"
    }
$sql .= implode(' AND ', $conditions);  // will produce condtion1 AND condition2 and so on

$sql .= ' ORDER BY table1.column';

在循环中,您还可以使用

定位特定元素
if(preg_match('/table1_/', $key)){
//populate conditions array
}

接下来,您可以根据需要进行修改。