-1

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']);

3 Answers3

0

You are not using the returned $con, do this in all your functions:

$con = db_connection();
Noman Ghani
  • 468
  • 3
  • 9
0

You're calling the db_connection function which returns the $con handler, but you are not assigning it's returned value to a variable.

Try amending to:

$con = db_connection();

Additionally, this $con assignment is also within a function, which means the variable will only be available within the scope of that function.

flauntster
  • 2,008
  • 13
  • 20
  • WOW, i cant believe i missed that. So ive fixed that, and for some reason it's still not inserting a record into the database in add_ip_to_db(). – GrnLight.net May 07 '14 at 07:30
  • Is it connecting to the db successfully? If so, echo out your sql query string and try running via phpMyAdmin or other db tool, or past the query here for us to inspect :) – flauntster May 07 '14 at 07:44
0

That's because $con is empty. It is local to the function. As soon as the function ends it's nowhere to be found. Assign a variable to db_connection();

$con = db_connection();
ksealey
  • 1,698
  • 1
  • 17
  • 16