PHP,MYSQL和超链接 - 从一个页面链接到一个详细页面(同一个表)[重复]
问题描述:
This question already has an answer here:
Not sure why this page doesn't seem to be working?
Trying to get the ID from the URL and use that to filter a table.
Example URL: http://example.com/page.php?id=123G
I'm getting 0 results when I type in that URL even though I know there is a match. Any ideas?
<html>
<head>
<style>table, th, td {border: 1px solid black;}</style>
</head>
<?php
$id = $_GET["id"];
$servername = "INSERTSERVER";
$username = "INSERTUSER";
$password = "INSERTPASSWORD";
$dbname = "INSERTDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$pd = "
SELECT fac_id, pd, phone_pd
FROM ft_location_db
WHERE fac_id = $id
";
$result = $conn->query($pd);
if ($result->num_rows > 0) {
echo "<table cellpadding=5 bgcolor=#FFFFFF><tr><th>PD</th><th>Phone</th>
</tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["pd"]. "</td><td>" . $row["phone_pd"]. "</td>
</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
</div>
答
Please, see the note in the bottom of the answer.
If fac_id
is a string datatype, it should be wrapped.
$pd = "
SELECT fac_id, pd, phone_pd
FROM ft_location_db
WHERE fac_id = '$id'
";
You have to use single quotes, because your query is written inside double quotes.
Using single quotes :
$pd = '
SELECT fac_id, pd, phone_pd
FROM ft_location_db
WHERE fac_id = "' . $id . '"
';
But (and -very- important), I suggest you to take a look to How can I prevent SQL injection in PHP? to secure your queries.
$stmt = $conn->prepare('
SELECT fac_id, pd, phone_pd
FROM ft_location_db
WHERE fac_id = ?');
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();
See also : bind_param()