Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the fatal error when fetching an assoc array

Tags:

php

mysqli

I am receiving a fatal error in my php/mysqli code which states that on line 46:

Fatal error: Call to undefined method mysqli_stmt::fetch_assoc() in ...

I just want to know how can I remove this fatal error?

The line of code it is pointing at is here:

$row = $stmt->fetch_assoc();

ORIGINAL CODE:

$query = "SELECT Username, Email FROM User WHERE User = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$user);
// execute query
$stmt->execute(); 
// get result and assign variables (prefix with db)
$stmt->bind_result($dbUser, $dbEmail);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();                                      

if ($numrows == 1){

$row = $stmt->fetch_assoc();
$dbemail = $row['Email'];

}

UPDATED CODE:

$query = "SELECT Username, Email FROM User WHERE User = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$user);
// execute query
$stmt->execute(); 
// get result and assign variables (prefix with db)
$stmt->bind_result($dbUser, $dbEmail);
//get number of rows
$stmt->store_result();
$numrows = $stmt->num_rows();                                      

if ($numrows == 1){    
  $row = $stmt->fetch_assoc();
  $dbemail = $row['Email'];    
}
like image 998
user1633219 Avatar asked Aug 29 '12 12:08

user1633219


1 Answers

The variable $stmt is of type mysqli_stmt, not mysqli_result. The mysqli_stmt class doesn't have a method "fetch_assoc()" defined for it.

You can get a mysqli_result object from your mysqli_stmt object by calling its get_result() method. For this you need the mysqlInd driver installed!

$result = $stmt->get_result();
row = $result->fetch_assoc();

If you don't have the driver installed you can fetch your results like this:

$stmt->bind_result($dbUser, $dbEmail);
while ($stmt->fetch()) {
    printf("%s %s\n", $dbUser, $dbEmail);
}

So your code should become:

$query = "SELECT Username, Email FROM User WHERE User = ?";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("s",$user);
// execute query
$stmt->execute(); 
// bind variables to result
$stmt->bind_result($dbUser, $dbEmail);
//fetch the first result row, this pumps the result values in the bound variables
if($stmt->fetch()){
    echo 'result is ' . dbEmail;
}
like image 52
Asciiom Avatar answered Sep 20 '22 18:09

Asciiom