myom
myom

Reputation: 135

Query two tables in MySQL to populate a PHP array

I am using two queries to select the values from their respective tables, and I want to put them into one array. For example, using the code below, I want to have

id, last, first, course1, course2, course3 

...from

$startsem1 and $endsem1 

...in one array.

$startsem1 = $startsem."reg";
$endsem1 = $endsem."reg";
$query = "SELECT id,last,first,course1,course2,course3 FROM $startsem1 
     UNION SELECT id,last,first,course1,course2,course3 FROM $endsem1";
$result = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_array($result))
    {
        print_r($row); echo "<br><br>";
    }

Upvotes: 1

Views: 1912

Answers (2)

Smandoli
Smandoli

Reputation: 7019

There are two approaches to merging your data sets:

  1. SQL UNION query
  2. array manipulation using array_merge() or another of the many PHP functions

The post suggests you want to use both at once. Actually you will select one.

If you use the second, a UNION query doesn't make sense because it produces one result. You need two separate queries, two results, two arrays.

If you use the first, you may still have array functions (such as array_merge()) or loop operations to clean up or resolve data issues.

Upvotes: 1

VolCh
VolCh

Reputation: 369

while ($row = mysql_fetch_array($result))
    {
        $array[] = $row;
    }
echo nl2br(print_r($array, TRUE));

Upvotes: 0

Related Questions