2

I have a database that has three tables with the same fields. I'm trying to get it to display the content, but I'm running into two issues. Here is what is on the PHP file. Can someone please help?

Issue 1: Only one table displays
Issue 2: If I add all tables and any have no data the out put is NULL

(I tried adding $query = "SELECT * FROM main_office,second_office,third_office"; but that didn't work.)

<?php
    class Location {
        public $address;
        public $city;
        public $us_state;
        public $zip;
        public $longitude;
        public $latitude;

    public function setAddress($address) {
        $this->address = $address;
    }
    public function setCity($city) {
        $this->city = $city;
    }
    public function setState($us_state) {
        $this->us_state = $us_state;
    }
    public function setZip($zip) {
        $this->zip = $zip;
    }
    public function setLongitude($longitude) {
        $this->longitude = $longitude;
    }
    public function setLatitude($latitude) {
        $this->latitude = $latitude;
    }
    }

header('content-type: application/json; charset=utf-8');

require 'config.php';

    $db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database) or die("Unable to select database: " . mysql_error());

$query = "SELECT * FROM main_office";
mysql_query("SET NAMES utf8");
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());

$rows = mysql_num_rows($result);

for ($j = 0 ; $j < $rows ; ++$j)
{
    $row = mysql_fetch_row($result);
    $location[$j] = new Location;
    $location[$j]->setAddress($row[5]);
    $location[$j]->setCity($row[6]);
    $location[$j]->setState($row[7]);
    $location[$j]->setZip($row[8]);
    $location[$j]->setLongitude($row[9]);
    $location[$j]->setLatitude($row[10]);
}

$json_string = json_encode($location); 
echo $json_string; 

?>
4

1 回答 1

1

我想你想要的union all操作:

SELECT *
FROM main_office
union all
select *
from second_office
union all
select *
from third_office;

这会将所有行附加在一起。您的原始版本是对表格进行笛卡尔积。也就是说,输出包含所有三个表中所有行的所有组合。因此,总行输出将是三个表中行的乘积。而且,一个表中没有行意味着没有行输出。

于 2013-08-07T02:29:11.747 回答