【问题标题】:Request to get the id from database is not working从数据库获取 id 的请求不起作用
【发布时间】:2017-12-25 04:49:20
【问题描述】:

大家好,我是 php 新手,我刚开始学习它我正在使用 xampp 本地服务器制作一个简单的电子商务网站,当我使用 get 方法检索一行的特定 ID 时,我遇到了这个问题:

  if (isset($_GET['id'])) {
           $id = mysqli_real_escape_string($_GET['id']);
                $sql = "SELECT * FROM items WHERE id= '$id'" ;
                $run = mysqli_query($conn, $sql) or die ('error');
              while($row=mysqli_fetch_array($run, MYSQLI_ASSOC)){
                  $discounted_price = $row['item_price'] - $row['item_discount'];

                  echo "
                       <div class='col-md-6'>
                       <h3 class='pp-title'>$row[item_title]</h3>
                       <img src='$row[item_image]' class='img-responsive' >
                       <div class='bottom'>

                       <div class='pull-right cutted-price text-muted'><del>$ $row[item_price]</del></div>
                       <div class='clearfix'></div>
                       <div class='pull-right disscounted-price'>$$discounted_price</div>
                       </div>
                       <h4 class='pp-dsc-title'>Description</h4>
                       <div class='pp-dsc-detail'>$row[item_description]</div>
                       </div> 

               ";
              }
           }else {
                echo "The request is not working";
            } 

我尝试访问的网址如下:

http://localhost/ec/items.php?item_title%20=%20Beautiful-brown-Watch&id%20=%201

如果我从上面删除 if 语句并简单地在查询中写入 id = '1' 或 '2' 数据出现在网页上,但当我这样做时,我会得到 else 输出“请求不起作用”一个特定的 ID 它不起作用我使用 mysqli_real_escape_string 来摆脱 SQL 注入,如果这不是摆脱 SQL 注入的正确方法,那么请指导我。

【问题讨论】:

  • mysqli_real_escape 不是避免 SQL 注入的方法。这个answer 有你需要知道的一切
  • 谢谢,我会试试这个准备好的语句
  • 您的错误消息意味着id 参数在$_GET 中不存在。您是否使用 http://localhost/foo.php?id=X 之类的名称调用您的 PHP 页面? (其中 X 是你想要的 id )
  • 是的,没错
  • @litelite 这是我的链接localhost/ec/…

标签: php mysqli xampp


【解决方案1】:

您正在检查$_GET 变量id,但您正在根据您的链接传入参数item_id

除此之外,您的查询字符串参数中还有额外的空格,这会导致您在 URL 中看到奇怪的 %20,因此请去掉这些空格。

要使其正常工作,您需要将 URL 更改为:

http://localhost/ec/items.php?item_title=Beautiful-brown-Watch&id=1 

或将您的代码更新为:

if(isset($_GET['item_id'])) {
   $id = mysqli_real_escape_string($_GET['item_id']);

您还需要检查参数化查询,因为mysqli_real_escape_string() 不是保证自己安全的方法。

可以在这里找到一篇很棒的帖子How can I prevent SQL injection in PHP?

【讨论】:

    【解决方案2】:

    您的代码需要一个名为 id 的参数,而您传递一个名为 item_id 的参数,将您的 URL 更改为

    http://localhost/ec/items.php?item_title=Beautiful-brown-Watch&id=1

    它应该可以工作。

    另请注意,创建 URL 时不应包含任何空格。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多