我有一个包含三个具有相同字段的表的数据库。我试图让它显示内容,但我遇到了两个问题。这是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;
?>
答案 0 :(得分:0)
我认为你想要union all
操作:
SELECT *
FROM main_office
union all
select *
from second_office
union all
select *
from third_office;
这会将所有行追加在一起。您的原始版本是表格的笛卡尔积。也就是说,输出由来自所有三个表的所有行的所有组合组成。因此,总行输出将是三个表中行的乘积。并且,一个表中没有行意味着不输出任何行。