Reputation: 11
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
.
P.S. I know that I need to use FB user ID instead of username, but in this case I need to do that.
Upvotes: 1
Views: 2414
Reputation: 426
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
}
Upvotes: 0
Reputation: 1487
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();
Upvotes: 1