How To Query Multiple Tables Jointly

Q

How To Query Multiple Tables Jointly? - MySQL FAQs - Managing Tables and Running Queries with PHP Scripts

✍: FYIcenter.com

A

If you want to query information stored in multiple tables, you can use the SELECT statement with a WHERE condition to make an inner join. Assuming that you have 3 tables in a forum system: "users" for user profile, "forums" for forums information, and "posts" for postings, you can query all postings from a single user with a script as shown below:

<?php
  include "mysql_connection.php";

  $userID = 101;
  $sql = "SELECT posts.subject, posts.time, users.name,
    . " forums.title"
    . " FROM posts, users, forums"
    . " WHERE posts.userID = ".$userID
    . " AND posts.userID = users.id"
    . " AND posts.forumID = forums.id";
  $rs = mysql_query($sql, $con);
  while ($row = mysql_fetch_assoc($rs)) {
    print($row['subject'].", ".$row['time'].", "
      .$row['name'].", ".$row['title']."\n");
  }
  mysql_free_result($rs);

  mysql_close($con); 
?>

2007-05-11, 5768👍, 0💬