PHP Mysql Left Join -
<?php $q = mysql_query("select sub_cat.*, links.* links left join sub_cat on links.p_id = sub_cat.id sub_cat.p_id = '$id' order name asc") or die (mysql_error()); while ($r = mysql_fetch_assoc($q)) { $links_name = $r['name']; $link_h3 = $links_name != '' ? '<h3>' . $links_name . '</h3>' : ''; //print $link_h3; print '<pre>'; print_r ($r); } ?> i have 2 tables rows like:
sub_cat
- id
- name
- p_id
links
- id
- links
- p_id
in sub cat have movie categories, foreign language movies, national movies, uncategorised movies , on. in links table have concrete movie links , depending on sub category.
the thing not want dublicate titles (sub_cat.name). result is:
without category www.moviesite.com
without category www.moviesite2.com
without category www.moviesite3.com
foreign movies www.moviesite1.bla
foreign movies www.moviesite2.bla
i want be
without category www.moviesite.com
www.moviesite2.com
www.moviesite3.com
foreign movies www.moviesite1.bla
www.moviesite2.bla
and not have idea how :(
any appreciated.
to job, have 2 solutions:
the first solution process data before showing it, in order group movies category.
you can example:
$moviesbycategory = array(); while ($r = mysql_fetch_assoc($q)) { // create new sub array new category if necessary if (!isset($moviesbycategory[$r['name']])) $moviesbycategory[$r['name']] = array(); // add movie in category $moviesbycategory[$r['name']][] = $r['links']; } and then, can iterate on new array like
foreach($moviesbycategory $category => $movies) { // print category name echo '<h1>' . $category . '</h1>'; // print movies of category foreach($movies $movie) echo '<h3>' . $movie . '</h3>'; } the second solution modify sql query group directly movies have same category. have use group by clause on sub_cat.id , apply agregate function on other fields in select.
for performance aspect, best solution sql solution, doing php give more flexibility presentation.
Comments
Post a Comment