I have a function which checks a db to see if an ip is registered on it, if it’s not then it logs the ip. If it is then it updates a count. Once the count goes over 3 the ip is 'blocked'.
Now I know that my IP is stored in the db so the first part of the function should skip but it doesn’t and I can’t explain why.
I tried the code out on a separate page so I could test the two outputs the functions relies on and they are working so I don’t know why the function is not working as it should.
Perhaps a fresh pair of eyes can stop my mistake!
Function that never goes past the first test even if the IP is stored and the query finds it...
Code: Select all
$db = new db_access;
//...
ip_fail($db,$b_ip); // calls the function
// Failed login attempt
function ip_fail(&$db,$b_ip) {
$query = "SELECT * FROM ip_block WHERE ip_add='$b_ip'";
$db->query_db($query);
$ip_d = mysql_fetch_row($db->q_result);
// Record IP if not on database
if ($db->q_rows() < 1) {
$query = "INSERT INTO ip_block(ip_add, count) VALUES ('$b_ip', 1)";
$db->query_db($query);
} else {
// Count attempts
if ($ip_d[2] < 3) {
$count = $ip_d[2] + 1;
$query = "UPDATE ip_block SET count='$count' WHERE ip_add='$b_ip'";
$db->query_db($query);
} else {
// Record block IP after 3 attempts
$timestamp = time();
$query = "UPDATE ip_block SET block='1', timestamp='$timestamp' WHERE ip_add='$b_ip'";
$db->query_db($query);
}
}
}
Code: Select all
<?
require_once("include/mysql_connect.php");
$b_ip = $_SERVER['REMOTE_ADDR'];
$db = new db_access;
function a(&$db,$b_ip) {
$query = "SELECT * FROM ip_block WHERE ip_add='$b_ip'";
$db->query_db($query);
$ip_d = mysql_fetch_row($db->q_result);
echo $ip_d[2]; // outputs 1 which is the count stored on the db
}
function b(&$db,$b_ip) {
a($db,$b_ip);
}
b($db,$b_ip);
echo $db->q_rows(); // outputs 1 which is the number of rows returned for the query
?>Code: Select all
// mysql_connect
class db_access {
public $db_hostname = 'localhost', $db_username = 'xxxxxxxx', $db_password = 'xxxxxxxx', $db_server, $q_result, $db_err,
$db_name = "scatty85_phptest";
// Constructor connect to server and select database
function __construct() {
$this->db_server = mysql_connect($this->db_hostname,$this->db_username,$this->db_password);
mysql_select_db($this->db_name);
}
// Query database
function query_db($query_string) {
$this->q_result = mysql_query($query_string);
}
// Number of rows from query
function q_rows() {
if ($this->q_result) {
return mysql_num_rows($this->q_result);
}
}
// Clean data
function mysql_entities_fix_string($string) {
return htmlentities(mysql_fix_string($string));
}
private function mysql_fix_string($string) {
if (get_magic_quotes_gpc()) $string = stripslashes($string);
return mysql_real_escape_string($string);
}
}