2015-06-14 48 views
1

我有4个变量(年份,月份,项目代码和类型)。PHP MySQL根据变量改变选择查询

因此,如果人提交的年度并保留其他3个变量的空白,然后选择查询必须 select * from table where year(trandate) = $var
但是,如果用户需要提供一年&月份则查询必须select * from table where year(trandate) = $var and month(trandate) = $var1

如果用户选择年月&工程代码并留下类型空白,然后查询必须为select * from table where year(trandate) = $var and month(trandate) = $var1 and projcode = $var3

依此类推。我怎么去编程这个,另外我会有很多组合?

希望问题清楚。

例如这是我迄今为止,但我可以看到,有太多的组合:

if (empty($ej1year) && empty($ej1month) && empty($ej1proj) && empty($ej1type)) { 
$rows = mysql_query("SELECT a.employee 
,a.trandate 
,CONCAT(a.workdone, '-', wc.BriefDescription) as WorkCodeActivity 
,CONCAT(a.custname, '-', cl.ShortName) as clientdet 
,a.qty 
,a.rate 
,a.amount 
,a.ref 
,a.projcode 
,a.type 
,a.qty*a.rate as costrate 
FROM transaction as a 
LEFT JOIN workcodes as wc ON a.workdone=wc.WorkCodeNo 
LEFT JOIN clients as cl On a.custname=cl.EntityNo"); 
} elseif (empty($ej1year) && !empty($ej1month)) { 
$rows = mysql_query("SELECT a.employee 
,a.trandate 
,CONCAT(a.workdone, '-', wc.BriefDescription) as WorkCodeActivity 
,CONCAT(a.custname, '-', cl.ShortName) as clientdet 
,a.qty 
,a.rate 
,a.amount 
,a.ref 
,a.projcode 
,a.type 
,a.qty*a.rate as costrate 
FROM transaction as a 
LEFT JOIN workcodes as wc ON a.workdone=wc.WorkCodeNo 
LEFT JOIN clients as cl On a.custname=cl.EntityNo 
where month(trandate) = '$ej1month'"); 

} elseif 

回答

2

像这样的东西应该工作:

<?php 
$where = array(); 
$binds = array(); 

if ($_POST['month'] !== '') { 
    $where[] = 'month = ?'; 
    $binds[] = $_POST['month']; 
} 
if ($_POST['year'] !== '') { 
    $where[] = 'year = ?'; 
    $binds[] = $_POST['year']; 
} 
... 

$query = 'select * from table where ' . implode(' AND ', $where); 
$db->execute($query, $binds); 

你要新增检查是否设置了任何变量。如果你不介意都是空的,你可以改变

$where = array();

$where = array(1);

将在查询最终成为“其中1”,实际上是选择了一切。

编辑:我看到你正在使用mysql_函数,这并不理想,因为they are deprecated。您应该尽快更新到PDO或mysqli。这里有一个版本,将使用mysql_

<?php 
$where = array(); 

if ($_POST['month'] !== '') { 
    $where[] = "month = '" . mysql_real_escape_string($_POST['month']) . "'"; 
} 
if ($_POST['year'] !== '') { 
    $where[] = "year = '" . mysql_real_escape_string($_POST['year']) . "'"; 
} 
... 

$query = 'select * from table where ' . implode(' AND ', $where); 
$result = mysql_query($query); 
+0

谢谢,会给它一个去,并报告输出 – Wilest

1

试试这个。

if (!empty($year) && empty($month) && empty($projectcode) && empty($type)){ 
    $query = 'select * from table where year(trandate) = $var'; 
}elseif (!empty($year) && !empty($month) && empty($projectcode) && empty($type)){ 
    $query = 'select * from table where year(trandate) = $var and month(trandate) = $var1'; 
}elseif (!empty($year) && !empty($month) && !empty($projectcode) && empty($type)){ 
    $query = 'select * from table where year(trandate) = $var and month(trandate) = $var1 and projcode = $var3' 
}