testkhan
testkhan

Reputation: 1787

getting multiple tables data with php

Suppose i have two tables... I want to get two tables data order by date posted/added or order by id!

so that if i have

table1
id msg              date
2  this is msg      nowdate

table2
id comment          date
2  this is comment  nowdate

Then how can i get it in single query order by id?

Upvotes: 1

Views: 171

Answers (2)

Sarfraz
Sarfraz

Reputation: 382861

 select t1.*, (t1.id) as id1, (t2.id) as id2, (t1.date) as date1, (t2.date) as date2, t2.* from table1 t1 inner join table2 t2 on t1.id = t2.id order by t1.id

 $arr = mysql_fetch_asssoc(above_query);
 echo $arr['id1'] // id of first table
 echo $arr['id2'] // id of second table
 echo $arr['msg'] // msg of first table
 echo $arr['comment'] // comment of second table
 echo $arr['date1'] // date of first table
 echo $arr['date2'] // date of second table

Upvotes: 2

Residuum
Residuum

Reputation: 12064

UNION is the word, you are looking for:

(SELECT * FROM table1) UNION (SELECT * FROM table2) ORDER BY id

Upvotes: 4

Related Questions