简体   繁体   English

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

[英]Check result of MySql count with if/else statement

Right, here's my code that limits the form submit rate. 是的,这是我的代码,用于限制表单的提交速度。 When the form is submitted it takes the timestamp and IP address, and then on page load this I have a SQL statement that takes the users IP, counts how many times it appears in the database in the past hour, and if it is 2 then the post box isn't displayed, else, it is, the problem is that it doesn't quite work, it just keeps showing the post box no matter what. 提交表单时,它带有时间戳和IP地址,然后在页面加载时,我有一条SQL语句,它获取用户IP,计算过去一个小时它在数据库中出现的次数,如果是2,则帖子框未显示,否则,问题是它无法正常工作,无论如何,它始终显示帖子框。 Here's the code: 这是代码:

<?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
}
?>

The $result does not yet contain the count in this case. 在这种情况下, $result尚未包含计数。 You must first fetch the resulting row from the resultset of the query, then you can compare. 您必须首先从查询的结果集中获取结果行,然后才能进行比较。

$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.');
   }
}

Use mysql_fetch_assoc($result) or mysql_fetch_array($result) Here is one example: 使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM