Jump to content

2 ul list from DB


Recommended Posts

Ok so I have a mysql query that returns a link description (Google) and an address (www.google.com). What I want is have all the links displayed in 2 equal ul list when total # of links are even and when odd there would be 1 more in the first list.I know this involves a loop but I'm unsure exactly how to do that.

Link to post
Share on other sites

something like this

//already have db data in 2 arrays $desc and $url$ul1 = '<ul>';$ul2 = '<ul>';for($i=0;$i<sizeof($desc);$i++){    if(($i % 2) == 0)    {        $ul1 .= '<li><a href="' . $url[$i] . '">' . $desc[$i] . '</a></li>';    }    else    {        $ul2 .= '<li><a href="' . $url[$i] . '">' . $desc[$i] . '</a></li>';    }}$ul1 .= '</ul>';$ul2 .= '</ul>';

Link to post
Share on other sites

What about the first part, right after I queried the DB. How do you split it in 2 arrays? what about when there is only 1 link?

Link to post
Share on other sites

You would have to loop through the dataset and just push everything into arrays. But you wouldn't necessarily have to do that either. You can replace this:for($i=0;$i<sizeof($desc);$i++)with the dataset loop, and just skip the middle man:

$ul1 = '<ul>';$ul2 = '<ul>';$i = 0;while ($row = mysql_fetch_assoc($result)){   if(++$i % 2)   {       $ul1 .= '<li><a href="' . $row['url'] . '">' . $row['desc'] . '</a></li>';   }   else   {       $ul2 .= '<li><a href="' . $row['url'] . '">' . $row['desc'] . '</a></li>';   }}$ul1 .= '</ul>';$ul2 .= '</ul>';

Link to post
Share on other sites

Works great!Is there a way to place the code echoed by php just as it would be in html in the source? Because if you take a look at the code in view source, it's all screwed up because of the php.

Link to post
Share on other sites

Well, it's not screwed up, there just aren't any linebreaks. You don't need linebreaks anyway though. Most of the time the output I send to the browser is all on one line, except for javascript. If you want to add line breaks, just add a "\n" after each line, but it has to be a double-quoted string, not single-quoted:

  if(++$i % 2)  {      $ul1 .= "<li><a href=\"" . $row['url'] . "\">" . $row['desc'] . "</a></li>\n";  }  else  {      $ul2 .= "<li><a href=\"" . $row['url'] . "\">" . $row['desc'] . "</a></li>\n";  }

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...