2013-12-20 27 views
0

正如標題中提到的,我想知道如何使查詢的數據成爲另一個php文件的鏈接。例如,參考以下附件中的圖片,我只想點擊它就可以顯示美國的所有城市,英國也是如此。我想讓我喜歡當我點擊任何狀態時,它的php文件鏈接將自動知道我選擇了哪個狀態並生成相應的城市。使查詢數據成爲鏈接

enter image description here

以下是我的代碼:

<html> 

    <head><title>State</title></head> 

<body> 

<?php 

$dbh = pg_connect("host=localhost dbname=state user=postgres"); 

if (!$dbh) { 
    die("Error in connection: " . pg_last_error()); 
} 

$sql = "SELECT * FROM state "; 



echo "<table>"; 
echo "<table border=\"1\" align=\"center\">"; 
echo "<tr>"; 
echo "<th>ID</th>"; 
echo "<th>State</th>"; 
echo "</tr>"; 


$result = pg_query($dbh, $sql); 

if (!$result) { 

    die("Error in SQL query: " . pg_last_error()); 

} 

while ($column = pg_fetch_array($result)) { 

echo "<tr>"; 
echo "<td>".$column[0]."</td>"; 
echo "<td>".$column[1]."</td>"; 
echo "</tr>"; 

} 

echo "</table>"; 


pg_free_result($result); 


pg_close($dbh); 


?> 

    </body> 

</html> 
+1

這並不難。你有什麼嘗試? –

+0

@JohnConde對不起,但我是新的...我可以創建正常的鏈接..但我不知道如何創建查詢數據的鏈接..可能是你善待給我一些指南...謝謝你提前! – green

+0

您需要使用錨標記來包裝該列,並且如果您將鏈接存儲在數據庫中,則可以使該錨源成爲該源。 –

回答

1
在當前的PHP文件

// Replace your while statement in your code above with this... 
$row_counter = 0; 
while ($row = pg_fetch_array($result,$row_counter,PGSQL_ASSOC)) { 

    echo "<tr>"; 
    echo "<td>".$row['id']."</td>"; 
    echo "<td><a href='state.php?id=".$row['id']."'>".htmlentities($row['state'])."</a></td>"; 
    echo "</tr>"; 

    $row_counter++; 
} 

而在另一個PHP文件,比方說state.php,你可以運行這樣的事情:

$state_id = $_GET['state_id']; 

// connect to database... 

$sql = "SELECT * FROM some_table WHERE state_id = '".pg_escape_string($state_id)."'"; 

// run your query... 

注意:htmlentities將防止XSS問題,pg_escape_string將有助於防止SQL注入(但研究prepared statements爲更好的方法)。

+0

非常感謝很多人..我正在檢查此 – green

+0

最終,你會想要分開你的PHP代碼從你的HTML碼。讓他們像這樣一起可以真正的混亂,真正快速。像「state.php」和「state_view.php」,其中state_view.php只有HTML和幾個PHP變量,或者最多隻有一個簡單的循環。你可以從state.php中「包含」這個文件,然後傳遞這些變量。理想情況下,您最終會創建某種類來處理將數據從PHP傳遞到您的視圖。研究MVC設計模式。祝你好運,選擇我的答案,如果它有幫助。 – prograhammer

+0

我也更新了我的答案,包括'htmlentities'(防範XSS)和'pg_escape_string'(防止SQL注入)。 – prograhammer