2013-08-07 63 views
1

我有一個數據庫有三個表具有相同的字段。我試圖讓它顯示內容,但我遇到了兩個問題。這是PHP文件上的內容。有人可以幫忙嗎?MYSQL&PHP顯示來自多個表的數據

問題1:只有一個表顯示
問題2:(我嘗試添加$query = "SELECT * FROM main_office,second_office,third_office";,但沒有工作),如果我的所有表添加任何沒有數據出來放是NULL

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

不要,我再說一遍,不要使用mysql_ *接口。切換到mysqli或PDO。它在最新的PHP版本中已被棄用。 –

回答

0

我想你想的union all操作:

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

這一切追加行在一起。你的原始版本是做表格的笛卡爾積。也就是說,輸出包含所有三個表中所有行的所有組合。所以,總的行輸出將是三個表中的行的乘積。而且,一個表中沒有行表示沒有行輸出。

+0

感謝您的幫助,解決了它。 – user2659008