简体   繁体   中英

How to check If user exists in MySQL database?

How to check if a user exists in the database already?

I have variable $name = $user_profile['name']; It successfully returns user's name.

And this is my part of code to check if user already exists in database.

$user_profile = $facebook->api('/me');
$name = $user_profile['name'];
$mysqli = new mysqli("asd", "asdf", "pw", "asdssst");
/* Create the prepared statement */
$stmt = $mysqli->prepare("SELECT COUNT(*) AS num FROM myTable WHERE userName = ?") or die("Prepared Statement Error: %s\n" . $mysqli->error);
/* Bind results to variables */
$stmt->bind_param('s', $name);
/* Execute the prepared Statement */
$stmt->execute();
$data = $stmt->fetch();
if ($data['num'] > 0) {
    echo "bad";
    print "user already exists\n";
} else {
    echo "good";
    $apiResponse = $facebook->api('/me/feed', 'POST', $post_data);
    print "No user in database\n";
}
/* Close the statement */
$stmt->close();

It always return: good No user in database whether user is in database or not. That means $data['num'] is always 0 .

PS I know that I need to use FB user ID instead of username, but in this case I need to do that.

I would use something like this

$mysqli = new mysqli('',"","","");
$query = 'SELECT username FROM user WHERE username = ?';
$stmt = $mysqli->prepare($query);
$name = 'asdf';
$stmt->bind_param('s', $name);
$stmt->execute();
$stmt->bind_result($user);
if($stmt->fetch())
   echo 'Username '.$user. ' exists';
else 
  echo 'User doesnt exists';
$stmt->close();

Check if the variable has a result to it. Something like this should work.

//So you have your variable $name here + it returns a value
$name = $user_profile['name'];
//You can put this if statement anywhere below it
if($name > 1){
//log user in
}

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