0

I'm using a javascript plugin this is the line which I need help from u

<script type="text/javascript"> 
   $('ul#news').newswidget({ source: ['http://rss.news.yahoo.com/rss/us', 'http://rss.news.yahoo.com/rss/world', 'http://feeds.bbci.co.uk/news/rss.xml'],

I would like to add URL data from MySQL I'm using it with while loop like this

     $('ul#news').newswidget({ source:[<?php
while($rssrow = mysql_fetch_array($rss))
{
     echo "'"."$rssrow[rss_name]"."'".",";
}
?>],

It doesn't work properly :(. I need to get like URL,URL,RUL like this. that means no comma for the last one

any one please help me

5 Answers 5

3

You can actually do that pretty easily by a simple reorganization:

if($rssrow = mysql_fetch_array($rss))
{
    echo "'".$rssrow['rss_name']."'";
    while($rssrow = mysql_fetch_array($rss))
    {
         // note no quotes -- they are redundant
         // prepend the comma
         echo ","."'".$rssrow['rss_name']."'";
    }
}

It does make for an extra step for the reader, but it does have the benefit of not needing substring, a new array, or a flag.

Sign up to request clarification or add additional context in comments.

Comments

2

You could just build the string and remove the last comma:

$result = '';
while($rssrow = mysql_fetch_array($rss))
{
     $result .= "'"."$rssrow[rss_name]"."'".",";
}

echo ($result != '') ? substr($result, 0, -1) : "''";

OR use implode():

$result = array();
while($rssrow = mysql_fetch_array($rss))
{
     $result[] = $rssrow[rss_name];
}
echo "'" . implode($result, "','") . "'";

(both of these methods will output '' if the result set is empty.)

Comments

1
$urls = "";

while($rssrow = mysql_fetch_array($rss))
{
    $urls.= "'$rssrow[rss_name]',";
}

echo substr($urls, 0, -1);

Comments

1

I wonder why no comment points out that you should definitely escape your output. If an entry contains a ', all solutions aside from Dmitry F’s first will break badly.

$('ul#news').newswidget({ source:[<?php
$arr = array();
while($rssrow = mysql_fetch_array($rss))
{
  $arr[] = '"' . str_replace('"', '\"', $rssrow['rss_name']) . '"';
}
echo implode(',', $arr);
?>],

Comments

1

here is a little bit different approach:

<?php
$news = array(
'source' => array(
    'http://example.com',
    'http://example.com'
)
);
$news_json = json_encode($news);
?>

<script>
$('ul#news').newswidget(<?php echo $news_json; ?>);
</script>

another variation:

$url = array();
while($rssrow = mysql_fetch_array($rss))
{
    $url[] = '"' . $rssrow['rss_name'] . '"';
}
echo implode(',', $url);

1 Comment

Your second version looses the first entry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.