1

我的 sysntax 是怎么回事,我做错了。有没有更好的办法?

<?
            $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
4

2 回答 2

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>"; 
于 2012-09-13T16:28:34.507 回答
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 语句并且您将遇到您报告的错误。

于 2012-09-13T16:41:36.810 回答