Take the 2-minute tour ×

This is my data

id          cost    cat         foreign     colours
385_white   99      swarovski   12          black;blue
386_white   99      swarovski   12          black;blue;green
387_white   99      swarovski   12          yellow;green
389_white   99      swarovski   12          white;silver
385_white   99      swarovski   12          silver

This is my query

$checkSQL=mysql_query("SELECT * FROM `products`");
while($r = mysql_fetch_array($checkSQL)) {
    echo '
        <ul class="ColourList">
            <li class="$row">$row</li>

Pseudo code - this should split the list into unique li

foreach ($r["colours"] as $key){
                        $key = explode(";", $r["colours"]);
                        <li class="$key"></li>

I want to create a list li item for each colour in the table row, so basically split the colon into separate rows - think it is explode?

share|improve this question
You could always try it and see. –  andrewsi Oct 1 '12 at 15:50
Your while loop isn't going to output correctly. since it is single-quoted. Variables ($row) won't be interpolated! –  Michael Berkowski Oct 1 '12 at 15:55
add comment

closed as not a real question by Bot, jeroen, dSquared, andrewsi, Sam Oct 1 '12 at 19:03


2 Answers

up vote 3 down vote accepted

This ought to do it :)

while($r = mysql_fetch_assoc($checkSQL)) {

    echo '<ul class="ColourList">';
    $cols = explode( ';', $r['colours'] );
    foreach ( $cols as $col ){
        echo '<li class="' . $col . '">' . $col . '</li>';
    echo '</ul>';
share|improve this answer
+1 Good answer and glad you changed mysql_fetch_array to mysql_fetch_assoc. Might want to point out the reason why you did that. Also, might want to point out that you shouldn't use mysql_* functions at all. Aside from that, this answer is fundamentally the same as the answer that I was going to post before you beat me to it :-) –  Travesty3 Oct 1 '12 at 16:03
add comment
$this->dbo = new mysqli(

$r = $this->dbo->query( "SELECT * FROM `products`" ) or die( $this->dbo->error );

while ( $r_items = $r->fetch_assoc() )
    echo '<ul class="ColourList">';
    foreach( explode(";" $r_items['colours']) as $r_color) {
        echo '<li class="' . $r_color . '">' . $r_color . '</li>';
    echo '</ul>';


I have provided this code instead of the original code as someone else already provided a good example of how to fix your code to make it work. This however is an example of mysqli, you should consider using mysqli instead of regular mysql simply for security reasons... I do not know the exact reasons but I have been told its best to use mysqli instead.

please forgive me if there are any errors in my code, this has not been tested but should work.

share|improve this answer
Pretty sure it needs to be $r[4], considering 0 = id, 1 = cost, 2 = cat, 3 = foreign, 4 = colour –  Set Sail Media Oct 1 '12 at 16:00
yep, my mistake, array starts on 0 :) thanks –  brenmoss Oct 1 '12 at 16:18
add comment
