tatty27
tatty27

Reputation: 1554

How to exclude last result in while loop so it can be treated differently php

I am using Google charts to display the results of db queries but on ie7 the carts don't display correctly because of an errant comma on the end of the last result fetched.

Is there a way to get the script to show all of the results except the last so that one can have the comma removed?

The code...

          google.load("visualization", "1", {packages:["corechart"]}); 
          google.setOnLoadCallback(drawChart); 
          function drawChart() { 
             var data = google.visualization.arrayToDataTable([ 
                      ['Error', 'Number'], 
              <?php 
                 $sql = "SELECT exposure_reasonID, COUNT(*) AS total FROM image 
                 WHERE exposure_reasonID != '' AND auditID = '$audit_id'
                 GROUP BY exposure_reasonID"; 
                 $result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli)); 
                  while($row = mysqli_fetch_array($result)){ 
                     echo "['".ucfirst(preg_replace_callback
                     ("/[a-zA-Z]+/",'ucfirst_some',$row['exposure_reasonID']))
                        ."',".$row['total']."],"; 
                     } 
               ?> 
            ]);

It is the comma at the end of the last line that appears to causing the issue

Upvotes: 1

Views: 92

Answers (1)

elixenide
elixenide

Reputation: 44851

Instead of echoing every line, build a string and echo a version of that without the comma:

google.load("visualization", "1", {packages:["corechart"]}); 
google.setOnLoadCallback(drawChart); 
function drawChart() { 
    var data = google.visualization.arrayToDataTable([ 
            ['Error', 'Number'], 
    <?php 
        $sql = "SELECT exposure_reasonID, COUNT(*) AS total FROM image 
        WHERE exposure_reasonID != '' AND auditID = '$audit_id'
        GROUP BY exposure_reasonID"; 
        $result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli)); 
        $output_str = ''; // this is new
        while($row = mysqli_fetch_array($result)){ 
           // add to the string instead of echoing each line
            $output_str .= "['".ucfirst(preg_replace_callback
                ("/[a-zA-Z]+/",'ucfirst_some',$row['exposure_reasonID']))
                ."',".$row['total']."],"; 
        }
        // strip the comma
        echo substr($output_str, 0, -1); // this is the critical change
    ?> 
  ]);

Upvotes: 1

Related Questions