简体   繁体   English

使用PHP,MYSQL进行动态查询

[英]Dynamic query using PHP, MYSQL

I'm trying to make a dynamic link which alters the database query depending on the items ID. 我正在尝试建立一个动态链接,该链接会根据项目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. 因此,如果单击链接“ ID = X”,它将带您到显示有关该项目的更多信息的下一页。 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 由于某种原因,问题似乎出在我的WHERE语句中

<?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" 例如,当我单击ID = 1的项目时,它会显示一条错误消息,内容为“查询错误:您的SQL语法有错误;请查看与您的MariaDB服务器版本相对应的手册,以找到在'附近使用正确的语法” = 1'在第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=.. 您的查询现在将为SELECT * FROM testWHERE ID=..

There needs to be a space between your tablename and the WHERE statement. 表名和WHERE语句之间必须有一个空格。

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. 在SQL中添加该空间将按原样修复您的查询,但是正如其他人所说的那样,您的代码并不安全,应改用准备好的语句。 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. 1)删除链接中所有不必要的空格。

<a href="details.php?ID=<?php print $row['ID']?>"> Click here </a>

2) Use prepared statements: see here . 2)使用准备好的语句: 请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM