views:

39

answers:

5

I am wanting to not echo out the comma at the end of the echo after the last row. How can I do that? Here is my code:

<?php
    header("Content-type: application/json");
    echo '{"points":[';

    mysql_connect("localhost", "user", "password");
    mysql_select_db("database");

    $q = "SELECT venues.id, venues.lat, venues.lon, heat_indexes.temperature FROM venues, heat_indexes WHERE venues.id = heat_indexes.venue_id";

    $res = mysql_query($q) or die(mysql_error());
    while ($point = mysql_fetch_assoc($res)) {
    echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'] . ",";
    }
    mysql_free_result($res);
    echo ']}';
    ?>
+1  A: 

Could you not use json_encode() instead, rather than hand-crafting the JSON?

$result = array();

//snip

while ($point = mysql_fetch_assoc($res)) {
    $result[] = $point['lat'];
    $result[] = $point['lon'];
    $result[] = $point['temperature'];
}

//snip

header("Content-type: application/json");
echo json_encode( array('points' => $result) );
Tom Haigh
Oh. I totally forgot about json_encode. Thanks!
Josh Brown
A: 

Use a count query to get the number of rows to begin with.

$query= "SELECT COUNT(*) FROM venues";
$count= mysql_query($q);

Then introduce a conditional and a count decrease each time through...

while ($point = mysql_fetch_assoc($res)) {
    $count = $count - 1;
    if ($count == 1) {
        echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
    } else {
    echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'] . ",";
    }
Scott
A: 

Json encode would probably be your best bet, but you could also use trim();

Rather than echoing in the while loop, append to a variable. Once outside the while loop, use $output = trim($output, ',') to remove trailing commas.

Josh
That is what I am going to use. Json_encode is working fine now and is exactly what I needed.
Josh Brown
A: 

About the comma problem, I always target the first item instead of the last:

$first = true;
while ($point = mysql_fetch_assoc($res)) {
    if ($first)
    {
        $first = false;
    }
    else
    {
        echo ",";
    }
    echo $point['lat'] . "," . $point['lon'] . "," . $point['temperature'];
}
jeroen
A: 

You can use mysql_num_rows() to find out how many rows are in the result set passed back from your last query.

...
$res = mysql_query($q) or die(mysql_error());
$num_rows = mysql_num_rows($res);

Then combine that with Scotts answer and you should be set.

thetaiko