如何向WHERE子句添加条件?

时间:2016-08-24 13:37:00

标签: php mysql

我需要使用c.statusRP = Open

中的状态过滤这些结果
  $query= mysql_query("SELECT h.id, h.sid, h.did, h.nextaction, h.nextactiondate, d.company, d.name, d.surname, c.company, d.balance, d.amount from History h, Person d, Client c where h.sid=c.ref and d.id=h.did and nextactiondate between $dayEnd and $dayStart order by c.company desc");

  #print $tquery;
  $mydate = date("d-m-Y");

  $message = "<br><br><h1>Task List for $mydate</h1><br>";

  $message .= "<table border=\"1\"><tr><strong><td>Customer Ref</td><td>Client Company</td><td>Customer Ref</td><td>Other Company</td><td>Full Name</td><td>Next Action</td></strong></tr>";

  while ($def = mysql_fetch_row($query)) {

    $sid = $def[1];
    $did = $def[2];
    $nextaction = $def[3];
    $nextactiondate = $def[4];
    $dcompany = $def[5];
    $dname = $def[6];
    $dsurname = $def[7];
    $ccompany = $def[8];
    $dbalance = $def[9];
    $damount = $def[10];

    if ($dbalance == "") {
        $newbalance = $damount;
    }
    else {
        $newbalance = $dbalance;
    }

    switch ($nextaction) {

我尝试过添加

$query= mysql_query("SELECT h.id, h.sid, h.did, h.nextaction, 
                            h.nextactiondate, d.company, d.name, 
                            d.surname, c.company, d.balance, 
                            d.amount 
                    from History h, Person d, Client c 
                    where h.sid=c.ref 
                      and d.id=h.did 
                      and nextactiondate between $dayEnd and $dayStart 
                    order by c.company desc 
                    WHERE c.statusRP = 'Open';");

然后我在显示此行的行上出现错误:

while ($def = mysql_fetch_row($query)) {

我做错了什么?

1 个答案:

答案 0 :(得分:2)

您已经有WHERE,需要将其加入AND,并将其放在ORDER BY之前。

$query= mysql_query("SELECT h.id, h.sid, h.did, h.nextaction, h.nextactiondate, d.company, d.name, d.surname, c.company, d.balance, d.amount 
    from History h, Person d, Client c 
    where h.sid=c.ref 
        and d.id=h.did 
        and nextactiondate between $dayEnd and $dayStart 
        AND c.statusRP = 'Open' 
        order by c.company desc;");

附加说明:$dayEnd$dayStart应该引用,除非它们是时间戳。

  

你对SQL注入非常开放。不推荐使用mysql_ *函数,并完全从PHP7中删除。切换到PDO或mysqli,并利用预处理语句和变量绑定,您不必担心引用。