I'm trying to make a dynamic link which alters the database query depending on the items ID.
So if you click on a link WHERE "ID=X" it takes you to the next page which displays more information about that item. Here is the code for the link on my index page:
<a href="details.php?ID= <?php print $row['ID']?> "> Click here </a>
Which works fine. The problem seems to be in my WHERE statement, for some reason
<?php $myQuery = "SELECT * FROM test";
$myQuery .= "WHERE ID=" . $_GET['ID'];
$result = $con->query($myQuery);
`if (!$result) die('Query error: ' . mysqli_error($con)); ?>
And here I display the elements of that particular database item...
<?php
while($row = mysqli_fetch_array($result))
{
?>
<?php print $row['image'] ?>
<?php print $row ['ID']?>
<?php print $row['description'] ?>
<?php
}
?>
For example when I click on the item with ID=1 it throws an error message that reads "Query error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '= 1' at line 1"
I'm really new to all this and this is my first time posting on this site so it'd be really great if someone could help me out.. Thanks
Your query will now be SELECT * FROM testWHERE ID=..
There needs to be a space between your tablename and the WHERE
statement.
I think it's clearer, and less error-prone if you write your code like this:
<?php $myQuery = "
SELECT *
FROM test
WHERE ID= $_GET['ID'];
";
...
although, in production you would of course use prepared statements
Adding that space in your SQL will fix your query as is, but as others have said, your code is not secure and you should use prepared statements instead. When you do switch to prepared statements your query will break again because of all the extra space you've added to the link. To fix it correctly ...
1) Remove all the unnecessary white-space in the link.
<a href="details.php?ID=<?php print $row['ID']?>"> Click here </a>
2) Use prepared statements: see here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.