1

is it possible to retrieve an array of data from more than one table within one query? For example , I am getting an array from table1, but I want to retrieve data from several other tables too:

<?php


   $con = mysql_connect($hostname,$username, $password);
   if (!$con)
     {
     die('Could not connect: ' . mysql_error());
   }
   mysql_select_db($dbname, $con);

   $today = date('Y-m-d H:i:s', time());
   $today1DayAgo = date('Y-m-d H:i:s', strtotime("$today -1 day"));
   $query = "SELECT * FROM table1 WHERE omtr_date BETWEEN '$today1DayAgo' AND '$today'";

   $result = mysql_query($query);

   while($row = mysql_fetch_array($result)){
       echo $row["omtr_page_view"]);
   }

   mysql_close($con);

  ?>

Thanks

friendlygiraffe
  • 871
  • 2
  • 6
  • 18
  • Please note that the `mysql_xx()` functions are deprecated and not recommended for use. You should switch to the `mysqli_xx()` functions or the PDO library as soon as possible. See also http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – SDC Jan 07 '13 at 11:53

3 Answers3

0

You can use joins to do this:

E.g.

SELECT t1.*, t2.id, t2.someothercolumn FROM table1 t1 LEFT JOIN table2 t2 ON t1.id=t2.t1_id WHERE omtr_date BETWEEN '$today1DayAgo' AND '$today'

(Untested)

Might be worth reading up on them.. http://www.sitepoint.com/understanding-sql-joins-mysql-database/

cowls
  • 24,013
  • 8
  • 48
  • 78
0

If your tables have something in common, like 1 column of table1 is the primary key of table2, or any kind of a relation (like same column), you can use JOINS.

Otherwise you can use UNION as well, like

SELECT omtr_date1.a AS a1, omtr_date1.b AS b1 FROM table1 WHERE omtr_date1 BETWEEN '$today1DayAgo' AND '$today'
UNION
SELECT omtr_date2.c AS a1, omtr_date2.d AS b1 FROM table1 WHERE omtr_date2 BETWEEN '$today1DayAgo' AND '$today'

But both the select statements must produce same number of columns with same column names.

That will do you good.

Tani
  • 115
  • 2
  • 14
0

Use Mysql Joins.

Here is an example:

<?php
// Make a MySQL Connection

// Construct our join query
$query  = "SELECT family.Position, food.Meal ";
$query .= "FROM family INNER JOIN food ";
$query .= "WHERE family.Position = food.Position";

//Execute query  
$result = mysql_query($query) or die(mysql_error());

// Print out the contents of each row into a table 
while($row = mysql_fetch_array($result)){
    echo $row['Position']. " - ". $row['Meal'];
    echo "<br />";
}
?>

More examples of mysql joins are listed here: http://phpweby.com/tutorials/mysql/32

Jirilmon
  • 1,924
  • 1
  • 12
  • 13