php - Testing if a Select Query found results -
hi i'm new php , appreciate if tell me i'm going wrong in code. put code in context, i'm using facebook authenticate users , adding signup details app database. in following code intend check if user exists in database , if not add them. reason can't test $result
i've checked query variables , echo out without problem
@ $con = new mysqli('localhost', 'username', 'password', 'database'); if(mysqli_connect_errno()){ echo 'error: not connect database. please try again later'; exit; } $query = "select * users oauth_provider = 'facebook' , oauth_uid ='".$uid."'"; $result = $con->query($query); if($result === false){ $insertquery = "insert ('oauth_provider', 'oauth_uid', 'username') values ('facebook', '".$uid."', '".$username."')"; $result = $con->query($query); }
i should add have code working using older mysql approach. have read better use object-oriented mysqli approach.
here's 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 database , table selected"; } $query = mysql_query("select * users oauth_provider = 'facebook' , oauth_uid = ". $user['id']); $result = mysql_fetch_array($query); if(empty($result)){ $query = mysql_query("insert users (oauth_provider, oauth_uid, username) values ('facebook', {$user['id']}, '{$user['name']}')"); $query = mysql_query("select * users id = " . mysql_insert_id()); $result = mysql_fetch_array($query); } }
any can give me appreciated.
if( $result instanceof mysqli_result && $result->num_rows==0)
break down:
$result instanceof mysqli_result
this ensure query go through , results return
$result->num_rows==0
this check previous query matching existing records
Comments
Post a Comment