[PHP & MySQL] Geting data from multi tables

Junior Spellweaver
Joined
Jan 4, 2011
Messages
138
Reaction score
12
Hello, I did search on this and i couldnt seem to find anything. With php & MySQL if you want to get two tables and disply all data from every table ordered by lets say the date. Would i have to get both tables as an array and use the array merge or is there a more simple/better way to do this?

Many thanks, Ashley Meah
 
Last edited:
foreach ($contents as $id=>$qty) {
$sql = 'SELECT * FROM putakoowns WHERE id = '.$id;
$result = $db->query($sql);
$row = $result->fetch();
extract($row);
$output[] = '<td><a href="putako.php?action=delete&id='.$id.'" class="r"><img src="/images/deletecart.gif" alt="delete" border="0"/></a>';
$output[] = '<td>'.$title.'</td><td>"'.$description.'"</td>';
$output[] = '<td class="red">$'.$price.'</td>';
$output[] = '<td><input type="text" name="qty'.$id.'" value="'.$qty.'" size="3" maxlength="3" /></td>';
$output[] = '</td>';
$total += $price * $qty;
$output[] = '</tr>';
}
Think this is what you need.

---------- Post added at 06:40 PM ---------- Previous post was at 06:37 PM ----------

************EDIT******************
THIS IS IT I THINK

SELECT summercamp.id summid,
<other fields from summercamp here>,
table2.table2id,
<other table 2 fields here>
FROM summercamp, table2
where summercamp.id = '.$id
and table2.id = summercamp.id
Just replace the summercamp with your stuff.
 
Thanks so i can select multi tables within the mysql query?

e.g.
$query = mysql_query("SELECT * FROM posts, pages ORDER BY id DESC");
 
thanks agian dont see why i havnt ever seen that before when i was learning about mysql_query(); lol.

say i use a while loop to get all the data, How would i disply the data if the two tables have diffrent fields? or is there away to disply this if this table and disply that if that table?
 
Last edited:
thanks agian dont see why i havnt ever seen that before when i was learning about mysql_query(); lol.

say i use a while loop to get all the data, How would i disply the data if the two tables have diffrent fields? or is there away to disply this if this table and disply that if that table?

I don't understand your question bro.
 
I don't understand your question bro.

Ok yets say a social network this time, I have 2 tables updates, pictures.

The updates have the rows id, update, date, time, author
The pictures have the rows id, image, capption, author

How would i show both of theses in a while loop and tell if its from the table updates or pictures to make it like facebook has everything under one feed.

This is an example i am not working on no social network. Many thanks, Ashley Meah
 
I suggest you use JOIN instead, it's more efficient and very dandy. You can read up on a tutorial here: MySQL Tutorial - Update

Anywho, I think it would be table1.column and table2.column. You can try that out, if it doesn't work, just read that tutorial.. The tutorial foxx posted is better, imo... We gave you the resources, have at it!

Aaron
 
Last edited:
Lemme show you a practical example of using JOIN, instead of trying to build it around your needs.

Say you have a table named "thread" and a table named "comments"

For each thread, there's going to be multiple comments. You need the thread data in order to identify the unique comments for a given page. Okay?

The thread has two important fields, "id", "title". The rest are unimportant here.

The comment table has a few important fields, "id", "thread_id", "content". The rest are unimportant here.

We want to grab a all the comments for a given thread, but don't want to run a whole query just to get the thread title. Here's a MySQL JOIN Statement:

Code:
SELECT thread_id, content FROM comments
JOIN thread ON(thread_id = thread.id)
WHERE thread_id = 1

If you missed this from Foxx, take another look:
SQL Joins
MySQL LEFT, RIGHT JOIN tutorial
MySQL Joins Tutorial | eHow.com
MySQL Join Tutorial | PHP

One of those ought to help you. Don't think it'll be easy or hard and you should be fine.
 
I dont think iv explained myself, i have 2 tables, with id, title, body, date, author, For data from tabel a i want to disply the body data and if its from tabel 2 i want t disply an image with the source as body. How would i get this in a while loop to disply both.

Like facebook has statuses recent releationship changes ect ect all in one stream, how do u disply diffrent data in diffrent ways from diffrent tables but ordered by an id or date ect.
 
You use JOIN, but then you have to pick an identifier. In my example case, it needs to be thread_id, because it's the only thing posts and threads share the same values (the query says to).

The while loop needs to realize, there's going to be multiples of $title, and $thread_id. If the $title or $thread_id change, it must be time for a new thread. If not, then continue placing the data from `post` table.

Here's a working example of utilizing JOIN via MySQLi to do this:

PHP:
<?php

// instantiation of MySQLi (does connecion, too)
$db = new mysqli( 'localhost', 'root', 'mysql root password', 'test' );

// get via thread ID
if( isset( $_GET['id'] ) )
{
	$join_query = 'SELECT thread_id, title, content FROM post 
		JOIN thread on(thread.id = post.thread_id)
		WHERE thread_id=?
		order by post.id';

// get all threads and posts
} else {
	$join_query = 'SELECT thread_id, title, content FROM post 
		JOIN thread on(thread.id = post.thread_id)
		order by thread.id, post.id';
}


//pre-defined output.
$output = '';

// If this query cannot be prepared
if(! $stmt = $db->prepare( $join_query ) )
{
	//Query cannot be prepared.. show why:
	die( 'MySQLi Error:' . $db->error );
}

//Note: If we've Made it this far, query can be prepared.

if( isset( $_GET['id'] ) )
{
	//put $_GET['id'] in query the right way:
	$stmt->bind_param( 'i', $_GET['id'] );
}

//execute prepared query:
$stmt->execute();

//bind $title, and $content to the results of query
$stmt->bind_result( $thread_id, $title, $content );

//define last_thread_id to nothing..
$last_thread_id = 0;

//fetch results from prepared query.
while( $stmt->fetch() )
{
	//If this is the first post in the thread:
	if( $thread_id != $last_thread_id )
	{
		//Begin thread:
		$output .= '<hr />';
		$output .= '<fieldset>';
		$output .= '<legend style="font-weight:bold">' . $title . '</legend>';
	
	//not the first post, must be a reply:
	} else {
		$output .= '<fieldset>';
		$output .= '<legend>Reply, </legend>';
	}
	
	//add the post itslef
	$output .= $content;
	
	//close the fieldset
	$output .= '</fieldset>';
	
	//define $last_thread_id as $thread_id for next loop.
	$last_thread_id = $thread_id;
}

//close the prepared query
$stmt->close();

//close the connection, we're done with MySQLi.
$db->close();
?>
<html>
<head>
	<title>Join Test</title>
	<style type="text/css">
	fieldset {
		width:250px;
		-moz-border-radius:1em;
		-webkit-border-radius:1em;
		border-radius:1em;
	}
	</style>
</head>
<body>
	<h1>Join Test</h1>
	<?php echo $output; ?>
</body>
</html>

The part you're looking for is within this loop: "while( $stmt->fetch() )"

This works to join threads with posts, whether it be 1 thread, or more than 1.

You can use this test DB to bang around, trying your own things:
Code:
-- phpMyAdmin SQL Dump
-- version 3.3.9
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Mar 24, 2011 at 07:23 PM
-- Server version: 5.5.8
-- PHP Version: 5.3.5

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: `test`
--

-- --------------------------------------------------------

--
-- Table structure for table `post`
--

CREATE TABLE IF NOT EXISTS `post` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `thread_id` int(11) NOT NULL,
  `content` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `post`
--

INSERT INTO `post` (`id`, `thread_id`, `content`) VALUES
(1, 1, 'Here''s a post in thread one'),
(2, 1, 'Here''s another post in thread 1'),
(3, 2, 'Here''s a post in Thread TWo'),
(4, 2, 'Another in Thread TWo');

-- --------------------------------------------------------

--
-- Table structure for table `thread`
--

CREATE TABLE IF NOT EXISTS `thread` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

--
-- Dumping data for table `thread`
--

INSERT INTO `thread` (`id`, `title`) VALUES
(1, 'This is Thread One'),
(2, 'This is Thread Two');

Hope this helps....
 
Last edited:
I still dont think u understand me, Example is say i have a post system, I would connect to a mysql server and database, Then query the table, in a while loop geting data from the rows you would have yets say:

<?php
mysql_connect("","","");
mysql_select_db("");
$query = mysql_query("SELECT * FROM posts");
while($row = mysql_fetch_array($query)){
echo "<b>" . $row["title"] . "</b><br>" . $row["content"];
}
?>

How would i also add yets say a downloads system...

<?php
mysql_connect("","","");
mysql_select_db("");
$query = mysql_query("SELECT * FROM downloads");
while($row = mysql_fetch_array($query)){
echo "<b>" . $row["title"] . "</b><br>" . $row["desc"] . "<br><br><a href='" . $row["dl"] . "'>Download Now</a>";
}
?>

I would also order each of these by date, but how would i get this all together ordered by date? So it show a post a post then a download ect ect. in order by the most recent date.
 
Code:
ORDER BY date

Also if you order by the IDs descending, they're in reverse-chronological order. (latest first)

For the last time, in MySQL, if you want to order two tables together you use JOIN.

I'm not posting again, you don't know it, but this is what you're asking for. Not sure if you're stating your question wrong- but this is the answer to your question.


Now you threw in Download feature.

That's different. If you want to let users download things from your site, you need to make a script that puts a header() that'll trigger a download (look it up).

Then you write the download to the file. That has nothing to do with mysql- unless you store the download as a blob in mysql. But you select it and order it like anything else in the db.
 
Code:
ORDER BY date

Also if you order by the IDs descending, they're in reverse-chronological order. (latest first)

For the last time, in MySQL, if you want to order two tables together you use JOIN.

I'm not posting again, you don't know it, but this is what you're asking for. Not sure if you're stating your question wrong- but this is the answer to your question.


Now you threw in Download feature.

That's different. If you want to let users download things from your site, you need to make a script that puts a header() that'll trigger a download (look it up).

Then you write the download to the file. That has nothing to do with mysql- unless you store the download as a blob in mysql. But you select it and order it like anything else in the db.

No i understand everything your saying already, I am realy bad at explaining, But i wana get BOTH of these together as one query to disply information for both of them ordered.

Like facebook shows people statuses link images ect. all slightly diffrent for displying videos, links normal statues ect.
 
I wanna say it again soooo bad... but I can't.. Stay calm... Woooosaaaaahhh

Pretty much, this statement:
"I want data from more than one table in MySQL"
leads us to JOIN. No matter which way you word it, JOIN (some form or another), is 99.9% of the time, going to produce the most efficient, simplest solution for this "multi-table" problem. (Which isn't a problem- JOIN is here to help.)

Edit: Coming with backup this time.

But i wana get BOTH of these together as one query to disply information for both of them ordered.
(Note: You can order any query- join or not.)

I Googled "two tables in one query"
SQL basics: Query multiple tables | TechRepublic


You were told previously you could do something along the lines of this:

http://www.techrepublic.com/article/sql-basics-query-multiple-tables/1050307 said:
Code:
SELECT table1.column1, table2.column2 FROM table1, table2 WHERE table1.column1 = table2.column1;
...

This syntax is, in effect, a simple INNER JOIN. Some databases treat it exactly the same as an explicit JOIN. The WHERE clause tells the database which fields to correlate, and it returns results as if the tables listed were combined into a single table based on the provided conditions.ah

...

JOIN works in the same way as the SELECT statement above—it returns a result set with columns from different tables. The advantage of using an explicit JOIN over an implied one is greater control over your result set, and possibly improved performance when many tables are involved.

Then, the query above can be best performed as:
Code:
SELECT table1.column1, table2.column2 FROM table1 INNER JOIN table2
ON table1.column1 = table2.column1;


Then there are subqueries:
Subqueries, or subselect statements, are a way to use a result set as a resource in a query. These are often used to limit or refine results rather than run multiple queries or manipulate the data in your application. With a subquery, you can reference tables to determine inclusion of data or, in some cases, return a column that is the result of a subselect.


The following example uses two tables. One table actually contains the data I’m interested in returning, while the other gives a comparison point to determine what data is actually interesting.
Code:
SELECT column1 FROM table1 WHERE EXISTS ( SELECT column1 FROM table2 WHERE table1.column1 = table2.column1 );
One important factor about subqueries is performance. Convenience comes at a price and, depending on the size, number, and complexity of tables and the statements you use, you may want to allow your application to handle processing. Each query is processed separately in full before being used as a resource for your primary query. If possible, creative use of JOIN statements may provide the same information with less lag time.


Click This Link ->
SQL basics: Query multiple tables | TechRepublic


Now then, I hope, you can figure this out..



Oh wait, almost forgot... ORDER BY....
ah ha!
online mysql tutorial, ordering data with MySQL ORDER BY clause, mysql select data statement

And theeerrrrreee yoouuu go.
 
Last edited:
  • Like
Reactions: Zen
Hey buddy, if you're saying you want something like Facebook's news feed, what you need is JOIN, it'll do the job.

Just try it.. If it's not what you want try to find a new way of explaining what you want! This will help us all. :P:
 
Last edited:
i understand what your all saying but you still aint understanding me, Iv got the first part but how will i know what table they where from so i can make it do this code if yets say an image and a diffrent code for videos ect ect.
 
Back