I have some PHP script querying a mysql database and echoing out a piece of javascript. Everything is working perfectly, except after echoing the last row of the query, I don’t want to echo a comma after the closing bracket. The result of the script should look something like this below, with the last line NOT ending with a comma.
{title: 'title1', url: 'mp3:mp3-1', start: 660, duration: 398},
{title: 'title2', url: 'mp3:mp3-2', start: 464, duration: 32},
{title: 'title3', url: 'mp3:mp3-3', start: 2956, duration: 139},
{title: 'title4', url: 'mp3:mp3-4', start: 653, duration: 62},
{title: 'title5', url: 'mp3:mp3-5', start: 1816, duration: 74}
As my code is now, the last line gets a comma just like the lines before it, and it is breaking my resulting javascript code (in IE only of course!!). I’m assuming the answer has to do with counting the number of rows left and if it’s greater then 1 echo one thing, and if it’s equal to 1 echo something else, I’m just not sure how to translate that into PHP code. Thanks for your help.
The code for the loop goes like this:
<?php
foreach($_SESSION['section_remember'] as $key =>$value)
{
$sql = "SELECT `section`.`start`,`section`.`stop`,`section`.`title`,`daily_show`.`audio_file`
FROM `section`
INNER JOIN `daily_show`
ON `section`.`daily_show_id` = `daily_show`.`id`
WHERE `section`.`id` = $value";
$result = mysql_query($sql);
while ($query = mysql_fetch_array($result))
{
$id = $query['id'];
$start = $query['start'];
$stop = $query['stop'];
$title = $query['title'];
$audio =$query['audio_file'];
$duration =$stop-$start;
echo"{title: '",$title;
echo"', ";
echo"url: 'mp3:",$audio;
echo"', ";
echo"start: ",$start;
echo", ";
echo"duration: ",$duration;
echo"}, ";
}
}
?>
Instead of keeping track of whether you are on the last row, you could just trim the trailing comma using
rtrim. All of thetrimming functions (trim, ltrim, rtrim) in PHP take a second parameter$charlistin which you can specify which characters to trim.