PHP mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, object given [duplicate]

孤人 提交于 2020-06-29 17:56:21

问题


I am trying to get all my results from a database into and array:

$sql = "SELECT * FROM posts WHERE user = ?";

if($stmt = mysqli_prepare($link, $sql)){
    // Bind variables to the prepared statement as parameters
    mysqli_stmt_bind_param($stmt, "i", $param_username_int);

    // Set parameters
    $param_username_int = $user;

    // Attempt to execute the prepared statement
    if(mysqli_stmt_execute($stmt)){

        mysqli_stmt_store_result($stmt);

        mysqli_fetch_assoc($stmt);

    }

    // Close statement
    mysqli_stmt_close($stmt);
}

When I try to fetch the results with this line:

mysqli_fetch_assoc($stmt);

I am expecting to get results into an array.

I get this error:

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, object given

回答1:


From the docs:

It is unnecessary to call mysqli_stmt_store_result() for other queries, but if you do, it will not harm or cause any notable performance loss in all cases.

Do you really need to use mysqli_stmt_store_result? If so, you need to bind variables and then get your data using mysqli_stmt_fetch, like so:

$stmt->execute();
$stmt->bind_result($postTitle, $postContent); //or whatever your db fields are

while ($stmt->fetch()) {
    printf ("%s (%s)\n", $postTitle, $postContent); //loop through all returned rows and display the post title and content
}

If not, you can use mysqli_stmt_get_result and then call mysqli_fetch_assoc on the result, like so:

mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt); //get result object
while ($row = mysqli_fetch_assoc($result)){ //get associative array

    /*Do whatever you want with result set here*/

}

Hope this helps!




回答2:


<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
$result=mysqli_query($con,$sql);

// Associative array
$row=mysqli_fetch_assoc($result);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);

// Free result set
mysqli_free_result($result);

mysqli_close($con);
?>


来源:https://stackoverflow.com/questions/47758379/php-mysqli-fetch-assoc-expects-parameter-1-to-be-mysqli-result-object-given

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!