简体   繁体   中英

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. 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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