html - Looping through MySQL select data with PHP if statements -
i'm trying return results database , output html. if feature=1 want image associated product display. underneath this, want title of results display regardless of value of feature. grouped release_date in variable $group_date
.
the code i've supplied @ bottom allows me retrieve data (i think down looping through 1 row , outputting before going on next, i'm not sure solution is):
group_date ----- ----- ----- |img| |img| |img| title ----- title ----- title ----- title group_date 2 ----- ----- ----- |img| |img| |img| title ----- title ----- title ----- title title
i results displayed this
group_date ----- ----- ----- |img| |img| |img| ----- ----- ----- title 1 title 2 title 3 title 4 group_date 2 ----- ----- ----- |img| |img| |img| ----- ----- ----- title 1 title 2 title 3 title 4 title 5 ....
here code have
<?php $dsn = "mysql:host=localhost;dbname=dbname;charset=utf8"; $opt = array( pdo::attr_errmode => pdo::errmode_exception, pdo::attr_default_fetch_mode => pdo::fetch_group ); $db = new pdo($dsn,"user", "pass", $opt); $stmt = $db->query("select * products order release_date asc, rating desc"); $group_date = ""; ?> <body> <div class="container"> <div> <div> <div id="contentwrapper"> <?php while( $row = $stmt->fetch(pdo::fetch_assoc) ) { if ($group_date !== substr($row["release_date"], 0, 10)) { $group_date = substr($row["release_date"], 0, 10); ?> <?=$group_date;?> <div> <?php } $feature= $row['feature']; if($feature=='1') {?> <a href="<?=$row['product_url']?>" title="<?=$row['title']?>"> <img src="<?=$row['img_url']?>" width='180' height='267' alt="<?=$row['title']?>"/> </a> <?php } ?> <?=$row['title']?> <br> <?php } ?> </div> </div> </div> </div> </div>
i have made few changes in code - please try , let me know. have saved titles in string , printed them when date being printed , re initialized "". have put //added in front of lines have put in code.
<?php $dsn = "mysql:host=localhost;dbname=dbname;charset=utf8"; $opt = array( pdo::attr_errmode => pdo::errmode_exception, pdo::attr_default_fetch_mode => pdo::fetch_group ); $db = new pdo($dsn,"user", "pass", $opt); $stmt = $db->query("select * products order release_date asc, rating desc"); $group_date = ""; $title = ""; //added ?> <body> <div class="container"> <div> <div> <div id="contentwrapper"> <?php while( $row = $stmt->fetch(pdo::fetch_assoc) ) { if ($group_date !== substr($row["release_date"], 0, 10)) { $group_date = substr($row["release_date"], 0, 10); ?> <?php echo $title == "" ? "" : $title; //added $title = ""; //added echo $group_date; ?> <div> <?php } $feature= $row['feature']; if($feature=='1') {?> <a href="<?=$row['product_url']?>" title="<?=$row['title']?>"> <img src="<?=$row['img_url']?>" width='180' height='267' alt="<?=$row['title']?>"/> </a> <?php } ?> <?php $title = $title . "<br>" . $row['title']; //added ?> <br> <?php } ?> </div> </div> </div> </div> </div>
Comments
Post a Comment