WHERE子句语法

时间:2012-09-13 16:28:03

标签: php mysql where-clause

我的语法有什么用,我无法做到。还有更好的方法吗?

<?
            $uid = $_GET["uid"];
            $month= $_GET["month"];
            $year = $_GET["year"];
            $query = "SELECT taskname,uid,month,year, SUM(tasktime) FROM tictoc WHERE uid = $uid, month = $month, year = $year GROUP BY taskname"; 

            $result = mysql_query($query) or die(mysql_error());

            // Print out result
            while($row = mysql_fetch_array($result)){
                echo "<br />";
                echo "Total ". $row['taskname']. " = <strong>". $row['SUM(tasktime)']."</strong>";
                echo "<br />";
            }
            ?>

错误是:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' month = 'Aug', year = '2012' GROUP BY taskname' at line 1

2 个答案:

答案 0 :(得分:9)

您需要使用AND,而不是逗号,如下所示:

select taskname, uid, month, year, SUM(tasktime)
from tictoc
where uid = $uid
    and month = $month
    and year = $year
group by taskname

另外,请注意以下几行:

echo "Total ". $row['taskname']. " = <strong>". $row['SUM(tasktime)']."</strong>"; 

不起作用。您需要在查询中为总和添加别名并引用该别名,如下所示:

SELECT taskname,uid,month,year, SUM(tasktime) as SumTaskTime

然后执行:

echo "Total ". $row['taskname']. " = <strong>". $row['SumTaskTime)']."</strong>"; 

答案 1 :(得分:1)

要补充上一个答案,请检查参数是否为空。例如:

 $uid = $_GET["uid"] = $_GET["uid"] == "" ? 0 : $_GET["uid"];
 $month = $_GET["month"] = $_GET["month"] == "" ? 0 : $_GET["month"];
 $year = $_GET["year"] = $_GET["year"] == "" ? 0 : $_GET["year"];

或选择您的检查策略。

原因是如果它们到达空并且您没有验证它,您将错误地构建您的SQL语句,并且您将报告您正在报告的错误。