Friday 17 November 2017

php - Fatal error to Call to a member function fetch_assoc() - why is fetch_assoc() is not working?

itemprop="text">

Here is the error DbOperations. php
codes:




public function
getUserByUserid($user_id){
$stmt = $this->con->prepare("SELECT * FROM
mydb.User WHERE user_id = ?" );
$stmt->bind_param("s",
$user_id);
return
$stmt->get_result()->fetch_assoc();
}


In
another userLogin.php, i use the getUserByUserid($user_id)
here:




if($db->userLogin($_POST['user_id'],
$_POST['password'])){
$user =
$db->getUserByUserid($_POST['user_id']);
$response['error'] =
false;
$response['user_id'] = $user['user_id'];
$response['name']
= $user['name'];
$response['contact_no'] = $user['contact_no'];

$response['email'] = $user['email'];
$response['role'] =
$user['role'];



And
this is the error
message:



Fatal
error
: Call to a member function fetch_assoc() on a non-object
in
C:\xampp\htdocs\Android\includes\DbOperations.php on
line
41



Line
41 is : return
$stmt->get_result()->fetch_assoc();




Not
sure what is the fetch_assoc() issue and i am a beginner...Thank you for
helping:)



Answer




You must execute
a query before trying to get results. Usually it is done with href="http://php.net/manual/en/mysqli-stmt.execute.php" rel="nofollow
noreferrer">execute:



public
function getUserByUserid($user_id){
$stmt = $this->con->prepare("SELECT
* FROM mydb.User WHERE user_id = ?" );
$stmt->bind_param("s",
$user_id);
// Executing a query

$stmt->execute();


return
$stmt->get_result()->fetch_assoc();
}


Going
further you can check if your execution completed succesfully
(get_result() returns not false in
this case) and in case of error - somehow get error message with
mysqli_errno() for example. More info (as
usual) in a href="http://php.net/manual/ru/mysqli-stmt.get-result.php" rel="nofollow
noreferrer">manual.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...