-2

I am trying to get the details of a person using their id, I have the following code and it's showing me an error.

$id = isset($_GET['id']) ? isset($_GET['id']) : "";
$sql = "SELECT * FROM `ArtListing` where `id` = $id";
$result = $conn->query($sql);

if (!$result) {
    die("Query failed " . $conn->error);
}

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo  $row["id"] . "." . $row["name"] ;
    }

If I use where the id is some random number like it gives me back the details. The error it's showing me is as following

Query failed You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    Why have you put that code in backticks (``)? – Ro Achterberg Nov 22 '20 at 10:09
  • 1
    If that query is throwing an error, then you are probably feeding it a non-integer (assuming the `id` column type is `INT`), presumably with one or more spaces in it. So `$id` probably doesn't hold the value you expect it does. For security and other reasons, you should be using prepared statements instead of variable expansion. See [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – Ro Achterberg Nov 22 '20 at 10:16
  • Note that the way you're building your query is unsafe. You're open to [SQL injection](https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work). You should use [prepared statements](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) instead. – El_Vanja Nov 22 '20 at 11:16
  • Does this answer your question? [How to include a PHP variable inside a MySQL statement](https://stackoverflow.com/questions/7537377/how-to-include-a-php-variable-inside-a-mysql-statement) – Dharman Nov 22 '20 at 14:11

2 Answers2

-1

It looks like the id you grabbing is undefined.

You should assign the $id variable as:

$id = isset($_GET['id']) ? $_GET['id'] : "0";
Neery
  • 55
  • 9
  • That is not the problem. An empty string is a perfectly correct value given that the empty string is expected. As we cannot see the database OP has we can't tell them to use 0 as the value – Dharman Nov 22 '20 at 14:12
-3

You cannot simply put variable inside a string You need to properly concatinate it to become a part of a sting as follows

$sql = "SELECT * FROM `ArtListing` where `id` = '".$id."'";

You can test this code here https://www.tehplayground.com/3HcoDppV0jAqdCYP

Take a look at combination of double quotes and single quotes.

Your SQL query string is created as follows

SELECT * FROM `ArtListing` where `id` = yourid; <-- incorrect

Whereas as per SQL syntax there should be single quotes

SELECT * FROM `ArtListing` where `id` = 'yourid'; <-- check single quotes around 'yourid'
skondgekar
  • 89
  • 4