Testing if a Select Query found results
Hi I'm new to PHP and would really appreciate if someone could tell me where I'm going wrong in this code.
To put the code in context, I'm using the facebook to authenticate users and adding their signup details to my app database.
In the following code intend to check if the user already exists in the database and if not add them.
For some reason I can't test the $result
I've checked the query variables and they echo out without a problem
@ $con = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()){
echo 'Error: Could not connect to the database. Please try again later';
exit;
}
$query = "SELECT * FROM users WHERE oauth_provider = 'facebook' AND oauth_uid ='".$uid."'";
$result = $con->query($query);
if($result开发者_StackOverflow社区 === FALSE){
$insertquery = "INSERT INTO ('oauth_provider', 'oauth_uid', 'username') VALUES ('facebook', '".$uid."', '".$username."')";
$result = $con->query($query);
}
I should probably add I have the code working using the older mysql approach. But I have read it is better to use the object-oriented mysqli approach.
Here's the old working code
if($session){
$con = mysql_connect('localhost', 'user', 'password');
$select_db = mysql_select_db('database');
if(!$con || !$select_db){
die('Could not connect: ' . mysql_error());
}
else{
echo "connected to database and table selected";
}
$query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook' AND oauth_uid = ". $user['id']);
$result = mysql_fetch_array($query);
if(empty($result)){
$query = mysql_query("INSERT INTO users (oauth_provider, oauth_uid, username) VALUES ('facebook', {$user['id']}, '{$user['name']}')");
$query = mysql_query("SELECT * FROM users WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
}
}
Any help you can give me is appreciated.
It can be done as simple as:
if($result)
{
// Do code when there are results
} else {
// Do code when there are no results
}
Use the MySQLi_Result::num_rows
property to get the number of rows of a MySQLi_Result object:
if ($result->num_rows > 0) {
// …
}
if( $result instanceof mysqli_result && $result->num_rows==0)
break down:
$result instanceof mysqli_result
this is to ensure query go through and results return
$result->num_rows==0
this is to check the previous query matching any existing records
精彩评论