I think for some reason $con is not getting filled with a connection, or db_connection() is not returning $con properly, because i always end up with this notice:
Notice: Undefined variable: con in ...
And i also get this error:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in ...
function db_connection(){
$username="username123";
$password="password1234";
$database="iptracker";
$con=mysqli_connect('localhost',$username,$password,$database);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
return $con;
}
function add_ip_to_db($user_ip){
//mysqli_close($con);
db_connection();
$current_time = date ('Y-m-d h:m');
mysqli_query($con,"INSERT INTO ips (ip, submit_count, date_time)
VALUES ('". $user_ip ."', 1, $current_time)");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
}
function add_count_to_db($user_ip){
//mysqli_close($con);
db_connection();
mysqli_query($con,"UPDATE ips ".
"SET submit_count = submit_count+1 ".
"WHERE ip = '". $user_ip ."'" );
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
}
function check_ip($user_ip){
db_connection();
$result = mysqli_query($con,"SELECT * FROM ips WHERE ip='". $user_ip."' LIMIT 1");
if(mysqli_fetch_array($result) !== false){
//Adding record to database
add_ip_to_db($user_ip);
} else {
//Update database and adding another count to 'submit_count'
add_count_to_db($user_ip);
}
}
check_ip($_SERVER['REMOTE_ADDR']);