title: display multiple rows from foreach result using json_encode
body: <p>I am working on a comment system, and I am trying to build a function that queries and displays 10 newest comments from database using ajax.</p>
  
  <p>The problem I am having is that, I just can't figure out how to display <strong>multiple</strong> rows using <strong>ajax</strong> and <strong>json_encode</strong>.</p>
  
  <p>When I display multiple rows with php, I use <code>.=</code>, which is so simple, but with ajax and json_encode, I can only display a single result with my knowledge so far.</p>
  
  <p>Below is the pure PHP version of my code to display multiple rows </p>
  
  <pre><code>public function display_comment(){
      $query = "SELECT * FROM 'comment' WHERE 'user_id' = $user_id ORDER BY 'save_time' DESC LIMIT 10";
      $result = $database-&gt;query($query);
  
      foreach($result as $row){
          $user_id = $row['user_id'];
          $user_name = $row['user_name'];
          $comment = $row['comment'];
  
          $all_comments .= '&lt;div id="' . $user_id . '"&gt;&lt;span&gt;' . $user_name . '&lt;/span&gt;&lt;span&gt;' . $comment . '&lt;/span&gt;&lt;/div&gt;';
      }
  }
  </code></pre>
  
  <p>Using ajax and json_encode, this is how I return a single result</p>
  
  <pre><code>public function display_comment(){
      $query = "SELECT * FROM 'comment' WHERE 'user_id' = $user_id ORDER BY 'save_time' DESC LIMIT 10";
      $result = $database-&gt;query($query);
  
      foreach($result as $row){
          $user_id = $row['user_id'];
          $user_name = $row['user_name'];
          $comment = $row['comment'];
  
          $json_array = array("user_id" =&gt; $user_id, "user_name" =&gt; $user_name, "comment" =&gt; $comment);
          header('Content-type:application/json');
          exit(json_encode($json_array)); // I am using exit instead of echo, because somehow if I use echo, it returns entire html page. 
      }
  }
  </code></pre>
  
  <p>jQuery part </p>
  
  <pre><code>$(document).on("click","#view_comment",function(e){
      e.preventDefault();
      $("#view_comment").text("loading..");
      var view_comment = $(this).val(); // Don't worry about this
  
      $.ajax({
          type:"post",
          data:{"view_comment":view_comment},
          dataType:"json",
          success:function(data){
              $('#ajax_comment').html('&lt;div id="' + data.user_id + '"&gt;&lt;span&gt;' + data.user_name + '&lt;/span&gt;&lt;span&gt;' + data.comment + '&lt;/span&gt;&lt;/div&gt;');
          },
          error:function(data){
              // Error code
          }
      });
  });
  </code></pre>
  
  <p>How should I change my code in order to display multiple rows using json_encode?</p>
  
  <p>Thank you so much in advance!</p>