-1

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>
Talsma
  • 37
  • 7
  • If the identifier is `123G`, `fac_id` column seems to be a string datatype, right? – Syscall Feb 27 '18 at 19:03
  • Yep is there a problem with that? It is unique. – Talsma Feb 27 '18 at 19:09
  • Actually figured this out. WHERE fac_id = $id needed to be WHERE fac_id = '$id' Very new to SQL and PHP. What is the deal with ' and "? Seems like I see things written different ways? – Talsma Feb 27 '18 at 19:11

1 Answers1

1

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()

Syscall
  • 19,327
  • 10
  • 37
  • 52