June 19, 2013

How to check if there aren't any result after querying and execute another statement?

K20GH’s Question:

I’m trying to do something fairly simple as per below. Basically, I want to check to see if a user exists using their ‘gid’. If they don’t exist, add them to the database, if they do, echo “User Already Exists”

For whatever reason, it will always add a new user, even if their gid exists.

$checkuser = "SELECT gid FROM user WHERE gid = '$id'";
$adduser = "INSERT INTO user (gid, name, pic) VALUES ('$id','$name','$img')";

if (!mysql_num_rows($checkuser))
{
    if (!mysqli_query($con,$adduser))
      {
      die('Error:  ' . mysqli_error($con));
      }
    echo "1 record added";
}
else {
    echo "User Already Exists";
    }

There is many things wrong with your code. First and the most important is you have a query a statement, if you do not query, you will not receive any result-set and the resultant is new registration every time.

Function is_resource() will help you decide whether or not the query
returns valid result.

Add here is the correct way to solve your problem.

$checkuser = "SELECT gid FROM user WHERE gid = '$id'";
$adduser = "INSERT INTO user (gid, name, pic) VALUES ('$id','$name','$img')";

$result = mysqli_query($con, $checkuser)); 
          // ^-- You have to query first to find out if there are any users or not

if(is_resource($result) && mysqli_num_rows($result) > 0) {
   // ^ This will confirm the query has returned a result and it contains rows

     echo "User Exists";
} else {
   // If it does not you can finally add it

     $result = mysqli_query($con, $adduser) or die(mysqli_error());
     echo "User added"; 
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!