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

时间:2011-10-19 08:52:57

标签: php mysql

是的,这是我的代码,它限制了表单提交率。提交表单时,它会获取时间戳和IP地址,然后在页面加载时,我有一个SQL语句,它接受用户IP,计算它在过去一小时内在数据库中显示的次数,如果是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
}
?>

2 个答案:

答案 0 :(得分:1)

在这种情况下,$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.');
   }
}

答案 1 :(得分:0)

使用mysql_fetch_assoc($result)mysql_fetch_array($result) 这是一个例子:

$query = 'SELECT count(*) FROM '.$table;
$result = mysql_query($query);
$res = mysql_fetch_array($result);
echo "Count - ".$res[0];exit;