简体   繁体   中英

Displaying a list with data from two tables

i have 2 tables that I would like to pull data from. The first table is called categories and structured like so:

---------------------------------
id  |   name            |  parent |
--------------------------------- |
1   |  Desktop Courses  |     0   |
2   |  Adobe            |     1   |
3   |  CS6              |     2   |
4   |  IT Courses       |     0   | 
5   |  Microsoft        |     4   |
6   |  Server 2008      |     5   |

I'm using the following code to display the data as a list:

<?php
  //Connect to mysql server
  $cn = mysql_pconnect("server", "username", "password");
  mysql_select_db("database");
  $rs = mysql_query("SELECT id, parent, name FROM course_categories", $cn);
  $childrenTree = array(); 
  $categoryNames = array(); 

  while($row = mysql_fetch_array($rs)){
     list($id, $parent, $name) = $row;     
     $categoryNames[(string)$id] = $name;
     $parent = (string)$parent;
     if(!array_key_exists($parent, $childrenTree)) 
         $childrenTree[$parent] = array();
     $childrenTree[$parent][] = (string)$id;
  }


 function renderTree($parentid = "0"){
    global $categoryNames;
    global $childrenTree;
    if($parentid != "0") echo "<li> ", $categoryNames[$parentid], "\n";
    $children = $childrenTree[$parentid];
    if(count($children) > 0){ //If node has children
       echo "<ul>\n";
       foreach($children as $child)
          renderTree($child);
       echo "</ul>\n";
    }
    if($parentid != "0") echo "</li>\n";
 }
 renderTree();  
?>

So this obviously pulls the data like this:

Desktop Courses
  Adobe
    CS6
IT Courses
  Microsoft
    Server 2008

Now I also have a table that displays the courses that is structured like this:

---------------------------------------------------
id    |      categoryid   |      course            |
---------------------------------------------------|
1     |          3        |       Photoshop CS6    |
2     |          6        |       Active Directory |

Now i'd like to merge the data from courses into the category list, but i'm not sure how to do it so that it would display like this:

Desktop Courses
  Adobe
    CS6
      Photoshop CS6
IT Courses
  Microsoft
    Server 2008
      Active Directory

Any help would be much appreciated.

Well, what you can try to do is just UNION ALL data from both tables like this:

SELECT id, parent, name, 'category' as `type` FROM course_categories
 UNION ALL
SELECT id, categoryid, course, 'course' as `type` FROM courses

Additional column type is added to the result set that you can distinguish between the categories and courses later on. That way you will leverage your existing php code. You'll need to do adjustments to accommodate this field though.

EDIT: The problem with this approach is that ids from both tables intersect. To alleviate this problem you might:

  • Shift courses' ids for a predifined value (let's say 1000).
SELECT id, parent, name, 'category' as `type` FROM course_categories
 UNION ALL
SELECT (1000 + id) AS id, categoryid, course, 'course' as `type` FROM courses
  • Define ids for categories and for courses from different ranges in the first place

To encourage you to consider switching from deprecated mysql_ to PDO here is how your data access code might look like:

<?php

$childrenTree = array(); 
$categoryNames = array();

//Connect to mysql server
$db = new PDO('mysql:host=server;dbname=db;charset=UTF-8', 'user', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$sql = "SELECT id, parent, name, 'category' as `type` FROM course_categories
         UNION ALL
        SELECT (1000 + id) AS id, categoryid, course, 'course' as `type` FROM courses";
foreach ($db->query($sql) as $row) {
     //your initial logic wrapped in the PDO row retrieval foreach loop
     list($id, $parent, $name) = $row;     
     $categoryNames[(string)$id] = $name;
     $parent = (string)$parent;
     if(!array_key_exists($parent, $childrenTree)) 
         $childrenTree[$parent] = array();
     $childrenTree[$parent][] = (string)$id;        
}
//close connection to the db
$db = null;

//Rest of your code goes here intact

Disclaimer: Error handling, validation, etc skipped for brevity.

select u_id, course_name, cat_id from (select id as 'u_id', name as 'course_name', parent as 'cat_id' from course_categories union select id as 'u_id', course as 'course_name', categoryid as 'cat_id')

希望这可以帮助

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM