MYSQL&;PHP显示来自多个表的数据


MYSQL & PHP Display data from multiple tables

我有一个数据库,它有三个具有相同字段的表。我正试图让它显示内容,但我遇到了两个问题。以下是PHP文件中的内容。有人能帮忙吗?

问题1:只有一个表显示
问题2:如果我添加了所有的表,并且任何表都没有数据,则输出为NULL

(我尝试添加$query = "SELECT * FROM main_office,second_office,third_office";,但没有成功。)

<?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; 
?>

我想您想要union all操作:

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

这会将所有行附加在一起。你最初的版本是做一个笛卡尔积的表。也就是说,输出由所有三个表中所有行的所有组合组成。因此,输出的总行数将是三个表中的行数的乘积。并且,一个表中没有行意味着没有行被输出。