title: Json encode an entire mysql result set
body: <p>I want to get json with php encode function like the following </p>
  
  <pre><code>&lt;?php 
    require "../classes/database.php";
  
    $database = new database();
    header("content-type: application/json");
    $result = $database-&gt;get_by_name($_POST['q']);   //$_POST['searchValue']
  
    echo '{"results":[';
    if($result)
    {
       $i = 1;
       while($row = mysql_fetch_array($result))
       {
          if(count($row) &gt; 1) 
          {
             echo json_encode(array('id'=&gt;$i, 'name' =&gt; $row['name']));
             echo ",";
          }
          else 
          {
             echo json_encode(array('id'=&gt;$i, 'name' =&gt; $row['name']));
          }
          $i++; 
       }
    }
    else
    {
       $value = "FALSE";
       echo json_encode(array('id'=&gt;1, 'name' =&gt; ""));  // output the json code
    }
  
    echo "]}";
  </code></pre>
  
  <p>i want the output json to be something like that </p>
  
  <pre><code>{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"}]}
  </code></pre>
  
  <p>but the output json is look like the following </p>
  
  <pre><code>{"results":[{"id":1,"name":"name1"},{"id":2,"name":"name2"},]}
  </code></pre>
  
  <p>As you realize that there is comma at the end, i want to remove it so it can be right json syntax, if i removed the <code>echo ",";</code> when there's more than one result the json will generate like this <code>{"results":[{"id":1,"name":"name1"}{"id":2,"name":"name2"}]}</code> and that syntax is wrong too</p>
  
  <p>Hope that everybody got what i mean here, any ideas would be appreciated </p>