hello all. i have this code...

<?php 
$query= "SELECT * FROM table"; 
$result=mysql_query($query) or die(mysql_error()); 
$num_rows = mysql_num_rows($result); 
if($num_rows > 0) 
{ 
    echo "<table>"; 
while($row = mysql_fetch_array($result)) 
    { 
    echo "<td>" . $row['data'] . "," . "</td>"; 
    } 
    echo "</table>"; 
} 
?>

lets say it is displaying from 5 records, it is displaying this way:

data1, data2, data3, data4, data5,

and i'd like it to be displayed without the comma following the last record and WITH an "&" preceding the last record in this way:

data1, data2, data3, data4, & data5

any ideas? i was told to do this...

"Maintain a counter in the while() loop that counts how many records have been outputted so far. Then, use an if() condition to check if the current count is one behind the total number of rows that your query returned (i.e. you're on the last row right now). If so, output the '&' separator. If not, output a comma instead."

...but i can't figure out how to accomplish this. can anyone provide me with an example of what i should be doing? thanks in advance.

<?php
$query= "SELECT * FROM table";
$result=mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
if($num_rows > 0)
{
echo "<table>";
while($row = mysql_fetch_array($result))
{
$num_rows--;
echo "<td>" . $row . ($num_rows > 0 ? "," : "") . "</td>";
}
echo "</table>";
}
?>

Member Avatar for diafol

Why do you want to create a table row if you're after a list?

@smantscheff
thanks alot. the code worked fine (even w/o the ampersand!) just kidding but if you get a chance can you give me a quick breakdown of what the red code you put in is doing (for learning purposes). thanks again.

@ardav
ive only been using php for a few months now and havent been exposed to all the different ways there are to perform different tasks. if you have an easier way please post it for me (i'd appreciate the learning experince!) thanks!

Member Avatar for diafol

I'm just curious as you're trying to create a simple list (x,y,z&a) but are using html tables <td>x</td><td>y</td><td>z</td><td>a</td>. I don't see how you can marry the two.

If fact the <td> method is pretty ropey if you don't know the number of items, unless you place a repeating counter to start new rows after a set number of cells.

$output="";$i=0;
while($row = mysql_fetch_array($result)){
  $output .= (($i != $num_rows) ? "," : "&") . $row['data'];
  $i++;
}
echo substr($output,1);

OK not as tidy as smant's but you get the &

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.