Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
716 views
in Technique[技术] by (71.8m points)

php - Call to undefined method mysqli_result::fetch()

I am able to fetch data from get_result() using any of fetch_assoc(), fetch_all(), ..., and fetch_row() but when I am trying to use the simple fetch() only, I am getting this error

Uncaught Error: Call to undefined method mysqli_result::fetch()

Is this because of using get_result()? or am I missing something else in the following code

$stmt = $conn->prepare($SQL);
$stmt->bind_param("s", $date);
$stmt->execute();
$result = $stmt->get_result();
//$row = $result->fetch_assoc();
//$row = $result->fetch_all();
//$row = $result->fetch_row();
$row = $result->fetch();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The variable $stmt is an object of the mysqli_stmt class. This class has a method called fetch() which returns a boolean (true/false). It is used only in conjunction with bind_result()

$stmt = $conn->prepare('SELECT myCol, myOtherCol FROM myTable WHERE dt=?');
$stmt->bind_param("s", $date);
$stmt->execute();
// The columns in SQL will be bound to the PHP variables
$stmt->bind_result($variable1, $variable2);
while ($stmt->fetch()) {
    // This will fetch each record from the prepared statement one by one
    printf ("myCol is %s and myOtherCol is %s
", $variable1, $variable1);
}

$stmt->get_result() returns an object of class mysqli_result (which by the way is traversable using foreach). This class has different methods, but it doesn't have fetch() method.

  • fetch_all() return an array of arrays. As the name suggests it returns all records from the result set at once.
    $result = $stmt->get_result();
    $allRecords = $result->fetch_all(MYSQLI_ASSOC);
    echo json_encode($allRecords);
    
  • fetch_array() returns each record one by one as an 1D array
    $row = $result->fetch_array();
    printf("%s (%s)
    ", $row["myCol"], $row["myOtherCol"]);
    
  • fetch_assoc() is the equivalent to fetch_array(MYSQLI_ASSOC)
  • fetch_row() is the equivalent to fetch_array(MYSQLI_NUM)
  • fetch_object() returns each record one by one as an object.
    $row = $result->fetch_object();
    printf("%s (%s)
    ", $row->myCol, $row->myOtherCol);
    

However, to keep it simple you can just loop on the mysqli_result directly which will get you each row as an associative array.

foreach($stmt->get_result() as $row) {
    printf("%s (%s)
", $row["myCol"], $row["myOtherCol"]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...