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

时间:2015-10-08 01:44:18

标签: php mysql comparison-operators

维护一个青年体育联盟网站,其中包含通过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 {

2 个答案:

答案 0 :(得分:1)

函数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]是一个整数。

答案 1 :(得分:1)

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

// 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返回结果的第一行作为关联数组,这使得它很好用且易于使用。 :)