我正在尝试创建一个使用PHP和MySQL的客户端类注册系统。我已经设置了数据库和表,并且该部分工作得很好,但是,客户端已经要求在注册时,如果有3个或更少的学生注册,以警告类可能无法运行。
我试图使用count()函数以及从cookie传递动态变量,从注册PHP脚本设置。然而,我遇到了一个障碍。我似乎无法让count()函数实际计算行数。我的select语句如下。如有任何帮助,我将不胜感激。
$class = $_COOKIE["class"];
$min_check = "SELECT class_list, COUNT(class_list) as count
FROM T_Student WHERE class_list = '$class'
GROUP BY class_list
HAVING count < 20";
$result = mysql_query($min_check);
$count = mysql_num_rows($result);
if ($count < 4)
{
echo "IF THERE ARE 3 OR FEWER PEOPLE SIGNED UP FOR THIS CLASS, IT MAY NOT RUN.'n";
echo "THERE ARE CURRENTLY " . $count . " PEOPLE SIGNED UP.'n";
}
else if ($count > 4)
{
echo "There are currently " . $count . " people signed up for this class.";
}
?>
您的SQL查询返回class_list
值的列表,以及每个特定实例的计数,其中注册的人数少于20人。
$count = mysql_num_rows($result);
…正在获取结果集中返回的记录数,而不是别名count
值,这就是您没有看到预期输出的原因。您需要读入结果集以获得值:
while ($row = mysql_fetch_assoc($result)) {
$count = $row['count'];
if($count < 4) { ... }
}
您想要的计数将在查询的行中返回。mysql_num_rows将对返回的行进行计数,这不是您想要的。
$result = mysql_query($min_check);
$count = mysql_fetch_row($result);
$count = $count[0];
乍一看,HAVING count < 20
是不必要的。
你使用MySQL-count-function,但从来没有检索它的值!?用途:
$firstRow = mysql_fetch_row($result);
$count = $firstRow[1]; // 1 indicates the second column (0 being the first)
我不建议使用已知的MySQL标识符,如count
。这是令人困惑的。
$class = mysql_real_escape_string($_COOKIE["class"]);
$min_check = "SELECT class_list, COUNT(class_list) as mycount
FROM T_Student WHERE class_list = '$class'
GROUP BY class_list
HAVING mycount < 20";
别忘了转义cookie的内容!
错误是这本身不是一个错误,但它只是太令人困惑了。count
是保留字。您需要用反引号`count`
包围它,或者更好的是,使用不同的名称。
接下来,您实际上并没有从数据库中检索mycount
结果。我建议使用这样的代码:
$result = mysql_query($min_check);
while( $row = mysql_fetch_assoc($result) ) {
$people_count = $row['mycount'];
if ($people_count < 4) { echo "this" }
else { echo "that" }
}