PHP比较运算符检查MySQL字段是否等于零


PHP Comparison Operator to Check If MySQL Field Equals Zero

维护一个青少年体育联赛网站,通过HTML前端显示时间表和排名,并使用PHP与MySQL后端数据库通信。几年来一切都很好,但我最近遇到了一个大问题,分数被无意中多次报告,我正试图填补允许它发生的漏洞。

下面是我试图添加到分数报告脚本的PHP代码的一小段摘录。这个想法是查询MySQL数据库,看看所选比赛的主客场比分当前是否为"0"。如果是,则还没有报告分数,脚本可以执行。但是,如果它们是任何其他值,那么我希望脚本停止。

在测试时,无论游戏是否被报告,脚本都会以"已经报告"的消息结束。我相信我有一个问题的比较操作符,我试图实现。谁能指出一些明显的代码,我似乎错过了?一个小小的指导将是非常感激!

// Check to see if game has already been reported:
$qh = "SELECT home_score FROM $table WHERE game_id=$row[0]";
$hscore = mysqli_query($db, $qh);
$qa = "SELECT away_score FROM $table WHERE game_id=$row[0]";
$ascore = mysqli_query($db, $qa);
if ($hscore != 0 || $ascore != 0) {
    echo "The scores for this game have already been reported. Please try refreshing your browser on the schedule page to verify.";
} else {

只需编写一个查询来获取两个分数,然后您可以轻松地比较它们以显示您所追求的内容。

// Check to see if game has already been reported:
$q = "SELECT home_score, away_score FROM $table WHERE game_id=$row[0]";
$result = mysqli_query($db, $q);
$scores = $result->fetch_assoc();
if ($scores['home_score'] != 0 || $scores['away_score'] != 0) {
    echo "The scores for this game have already been reported. Please try refreshing your browser on the schedule page to verify.";
} else {

fetch_assoc()方法获取从MySQL返回的结果的第一行作为关联数组,这使得它很好且易于使用。:)

函数mysqli_query返回一个mysqli_result object,因此您需要获取它以获得实际值。我想这个可以。

$qh = "SELECT home_score FROM $table WHERE game_id=$row[0]";
$hscore = mysqli_stmt_fetch(mysqli_query($db, $qh));
$qa = "SELECT away_score FROM $table WHERE game_id=$row[0]";
$ascore = mysqli_stmt_fetch(mysqli_query($db, $qa));
if ($hscore['home_score'] != 0 || $ascore['away_score'] != 0) {
    echo "The scores for this game have already been reported. Please try refreshing your browser on the schedule page to verify.";
} else {

另一种方法是确保得分大于0。

SELECT home_score FROM $table WHERE game_id=$row[0] and home_score > 0

然后你需要知道如果你得到一行分数大于0。

我认为这种方法是你最好的方法,尽管(未经测试).

$qh = "SELECT home_score, away_score FROM $table WHERE game_id=?";
$hscore = mysqli_prepare($db, $qh);
mysqli_stmt_bind_param($hscore, 'i', $row[0]);
mysqli_stmt_execute($hscore);
$unique_row = mysqli_fetch_row($hscore);
if ($unique_row['home_score'] != 0 || $unique_row['away_score'] != 0) {
    echo "The scores for this game have already been reported. Please try refreshing your browser on the schedule page to verify.";
} else {

假设$row[0]为整数