dronthpi05943 2016-07-27 07:04
浏览 460
已采纳

mysqli_fetch_assoc仅返回数组的第一个元素

I'm working on a project, where the logged in user should be able to post notes on the homepage, and being logged in the certain user's notes should be printed above the new note form. I've written a function for that, where the mysqli_query recognizes all the 6 entries I have, but the mysqli_fetch_assoc prints only the first note out of 6. What could I do wrong? Here is my code:

<?php    
    function find_notes_by_id($user_id) {
    global $connection;
    
    $safe_user_id = mysqli_real_escape_string($connection, $user_id);
    
    $query = 'SELECT content ';
    $query .= 'FROM notes ';
    $query .= 'WHERE user_id = '.$safe_user_id;
    $result = mysqli_query($connection, $query);
 
    //mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 6 [type] => 0 )

    confirm_query($result);

    $row = mysqli_fetch_assoc($result);
    //Array ( [content] => First! ) = it only shows the very first element
    return $row;
}
?>

<?php
$notes_set = find_notes_by_id($userRow['id']);
  foreach($notes_set as $note){
    echo $note;
    echo "<br />";
  }
?>

enter image description here

</div>
  • 写回答

6条回答 默认 最新

  • doubinchou4219 2016-07-27 07:09
    关注

    1.You need to iterate over your result-set object through while()

    2.Save all your data to an array and then return that array to get all records

    like below:-

    <?php    
      function find_notes_by_id($user_id) {
       global $connection;
    
        $safe_user_id = mysqli_real_escape_string($connection, $user_id);
    
        $query = "SELECT `content` FROM `notes` WHERE `user_id` = $safe_user_id";
        $result = mysqli_query($connection, $query);
    
        confirm_query($result);
    
        $final_data = array(); // create an array
        while($row = mysqli_fetch_assoc($result)){ // iterate over the result-set object to get all data
            $final_data[] = $row; //assign value to the array
        }
        return $final_data; // return array
      }
    ?>
    

    Now:-

    <?php
    $notes_set = find_notes_by_id($userRow['id']);
    
    print_r($notes_set) ; // print result to check array structure so that you can use it correctly in foreach
      foreach($notes_set as $note){
        echo $note['content'];
        echo "<br />";
      }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab