php - 使用 if/else 语句检查 MySql 计数结果

标签 php mysql

好的,这是我限制表单提交率的代码。提交表单时,它采用时间戳和 IP 地址,然后在页面加载时,我有一个采用用户 IP 的 SQL 语句,计算过去一小时内它在数据库中出现的次数,如果是 2 次,则邮箱不显示,否则,问题是它不能正常工作,无论如何它都会一直显示邮箱。这是代码:

<?php

$IP = $_SERVER['REMOTE_ADDR'];
$sql = "select count(*) from mysql_table where ip='$IP' and timestamp > (DATE_ADD(now(), INTERVAL -1 HOUR))"; 
$result = mysql_query($sql) or print mysql_error();

if ($result['count(*)'] == 2) {
die('You are out of posts this hour.');
}

else {
?>

<font style="position:relative; margin: 0 auto; top:15px; color:#fff; font-size:16px; font-family:Arial;">Note, once you have posted, it <b>CANNOT</b> be removed.</font>
<div id="postbox">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<textarea id="postbox" name="postbox"></textarea><br />
<input type="checkbox" name="allowcommenting" value="1" id="commenting" CHECKED ><font style="margin-right:45px; font-family:Arial; font-size:18px; color:#fff; position:relative; top:15px;">Allow commenting?</font>
<?php
            require_once 'math-security.php';

            $math = new BasicMathSecurity( 'math' );
            echo $math->getField();
?>
<input type="submit" name="submit" id="submit" value="Share" value="This cannot be undone." />
</form>
</div>

<?php
}
?>

最佳答案

在这种情况下,$result 还不包含计数。您必须先从查询的结果集中获取结果行,然后才能进行比较。

$sql = "select count(*) from mysql_table where ip='$IP' and timestamp > (DATE_ADD(now(), INTERVAL -1 HOUR))"; 
$result = mysql_query($sql) or print mysql_error();
if($row = mysql_fetch_row($result)) {
   if ($row[0] == 2) {
      die('You are out of posts this hour.');
   }
}

关于php - 使用 if/else 语句检查 MySql 计数结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7818803/

相关文章:

php - symfony 表单事件订阅者 $event->getData() 返回 NULL

mysql - 组与用户的直接关联

php - 创建用户角色

mysql - 如何将列名与其他参数一起传递

不能为空的 MySQL 数据类型?

c# - ServiceInterface 中的 ServiceStack Ormlite 使用

mysql show variables like 'innodb%' 什么都没返回

php - 选择 LAST_INSERT_ID() *更新

php - SQL 在数据库中搜索文本正文中的短语

php - 使用simplexml解析特殊字符xml文件