PHP foreach statement within MySQL select query
This ought to do it :)
$checkSQL=mysql_query("SELECT * FROM `products`");
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>';
}
TheBlackBenzKid
Ecommerce specialist with 15+ years of experience in development, design, marketing and management. Application Acceleration CDN, Load balancing and performance NodeJS, Vanilla JS, AngularJS IBM WebSphere Commerce Fast Fashion advocate - love ecommerce, love luxury fashion Oracle ATG Web Commerce OPENCART Stack: NodeJS, PHP, NGINX, Smarty or a JS view framework Omni channel and mutli channel advocate PHP/MySQL/HTML5/CSS3/JavaScript/Nginx/Rackspace/AWS/jQuery/SaSS also GULP over WebPack (some fanboy love for ya!) oh.. and DEFO FLASH and GIF! As Gif and Flash will always come back with a boom! 2018 Big fan of Blockchain, Cryptography, Hash graph and block chain development
Updated on June 04, 2022Comments
-
TheBlackBenzKid almost 2 years
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> </ul> '; }
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 isexplode
? -
Patrick Moore over 11 yearsPretty sure it needs to be
$r[4]
, considering 0 = id, 1 = cost, 2 = cat, 3 = foreign, 4 = colour -
Travesty3 over 11 years+1 Good answer and glad you changed
mysql_fetch_array
tomysql_fetch_assoc
. Might want to point out the reason why you did that. Also, might want to point out that you shouldn't usemysql_*
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 :-) -
Admin over 11 yearsyep, my mistake, array starts on 0 :) thanks