php - Mysqli fetch 仅返回一个值

标签 php mysql arrays mysqli

我不知道为什么这个函数只返回一个值,而数据库中有两个值,id 为 6 和 7 。

 function get_posts(){
     $msg = "";

  if ($countm = $mysqli->prepare("SELECT    SQL_CALC_FOUND_ROWS id,post_userid,name,lang,country,post_image,post_date,post_date_updated FROM posts  ORDER BY `post_date` DESC ;")) {
    $countm->execute(); // Execute the prepared query.
    $countm->store_result();
    $countm->bind_result($id,$post_userid,$name,$lang,$country,$post_image,$post_date,$post_date_updated); // get variables from result.
    $nr = "SELECT FOUND_ROWS() ";
    $r = $mysqli->prepare($nr);
    $r->execute();
     $r->bind_result($no_posts);
     $r->fetch();
     $r->close();
    while ($l[] = $countm->fetch())
    {
       $msg .= ' <tr><td>'. $id .'</td>';
       $msg .= ' <td>'. $post_userid .'</td></tr>';

    } ; 
    $countm->close();
    }else {printf("Prepared Statement Error: %s\n", $mysqli->error);}
return array('msg' => $msg, 'no_posts' => $no_posts);
}

我已经在数据库中测试了sql,它工作正常,它返回两个值。但是当我使用这个函数时,我只得到一个值。

我就是这样使用这个函数的

  $get_posts = get_posts();
  echo $get_posts['msg'];    // returns 1 value

有什么想法吗?

  fetchAll()   fetch_all()  fetch_array() .... all not working im getting this error when using them

  Call to undefined method mysqli_stmt::fetchAll() in...

最佳答案

你的代码看起来有点乱。我建议你尝试这个更简单的代码版本来检查你是否真的得到了你想要的这两行:

if ($countm = $mysqli->prepare("SELECT id,post_userid,name,lang,country,post_image,post_date,post_date_updated FROM posts  ORDER BY `post_date` DESC ;")) 
{
    $countm->execute();
    $countm->bind_result($id,$post_userid,$name,$lang,$country,$post_image,$post_date,$post_date_updated);
    while ($countm->fetch()) {
       $msg .= ' <tr><td>'. $id .'</td>';
       $msg .= ' <td>'. $post_userid .'</td></tr>';
    }
    echo $msg;
}

关于php - Mysqli fetch 仅返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47579347/

相关文章:

mysql - 如何在Mysql中同时获取数据

php - 如何在每次迭代中以从上到下的方式旋转数组元素

php - 在我的新代码中对非对象执行 bind_param() 函数

php - UTF-8贯穿始终

php - mytheme/update.php 中的 wordpress 查询

java - 在for循环java中为json对象添加值

c - 如何设置一个数组等于 char* 方法的返回值

php - 减少mysql中的一整列

PHP/MySQL - 在哪里可靠地处理插入自动重新请求(锁定表) - 客户端还是服务器?

mysql - Rails 中的 SQL-IN 操作符多次出现相同的 ID