Jump to content

How to Prevent While Loop from Affecting Last DB Result


sandbox

Recommended Posts

Hi everyone,

 

Okay, so I'm using the following code to extract my navigation pages from a DB and display them in the footer of the page. My aim is to add an " | " between each link which I have achieved, but as it stands, it also adds an " | " after the last result which is not the affect I'm looking for. Does anybody know a way in which to prevent this?

 

Thanks for taking the time to help. :)

 

 

<?php
    $sql = "SELECT *
	    FROM `navigation`
	    ORDER BY position ASC";
							
    $qry = mysql_query($sql);
							
    confirm_query($qry);
							
    while ($res = mysql_fetch_array($qry)) {
									
    echo "<a href=\"{$res['url']}\">" . $res['page'] . "</a>";
    echo " | ";
    }
?>

 

There are two (well, three actuall) methods I can think of:

 

1. Don't echo the values to the page directly. Instead append the text to a variable. Then when the loop completes, use substr() to remove the last three characters from the variable before echoing to the page.

 

2. Create the code for the individual links as elements in an array - then implode the results using the delimiter of " | ".

 

3. The third solution is to use GROUP_CONCAT in the query to return the results as a single concatenated value. But, you would also have to use string functions to have the query automatically generate the HTML code. That's possible, but it's not a good idea to hard-code presentation logic into your DB queries. So, while this is possible, probably not a good idea.

 

I prefer #2

<?php
    $sql = "SELECT *
        FROM `navigation`
        ORDER BY position ASC";
    $qry = mysql_query($sql);

    confirm_query($qry);

    $links = array();
    while ($res = mysql_fetch_array($qry))
    {
        $links[] = "<a href=\"{$res['url']}\">{$res['page']}</a>";
    }

    echo implode(" | ", $links);
?>
 

I've actually done efficiency testing on this and #1 is the most efficient. The difference is negligible to a fairly large number of loops, so personal choice weighs more for most situations.

 

Also, it is helpful to know (if you didn't) that a negative value can be passed as the length for substr():

$sql = "SELECT *
	FROM `navigation`
	ORDER BY position ASC";
					
$qry = mysql_query($sql);
					
confirm_query($qry);
		
$out = '';
while ($res = mysql_fetch_array($qry)) {					
	$out .= "<a href=\"{$res['url']}\">" . $res['page'] . "</a> | ";
}
echo substr($out, 0, -3);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.