使查询数据成为链接

时间:2013-12-20 02:28:42

标签: php html postgresql

正如标题中所提到的,我想知道如何使查询的数据成为另一个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 :(得分: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以获得更好的方法)。