PHP MySQL根据变量更改选择查询

时间:2015-06-14 15:38:42

标签: php mysql

我有4个变量(年,月,项目代码和类型)。

因此,如果此人提交年份并将其他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 个答案:

答案 0 :(得分: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);

最终将成为&#34;其中1&#34;在查询中,有效地选择所有内容。

编辑:我发现你使用的是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);

答案 1 :(得分: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'
}