2017-07-19 26 views
0

嗨,大家好我是新的php我剛開始學習它我正在使用xampp本地服務器製作一個簡單的電子商務網站我正在面對這個問題,當我使用get方法檢索行的特定ID:請求從數據庫中獲得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"; 
      } 

我試圖訪問該上的URL是如下所示:

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

我收到其他輸出「的要求是不工作」如果我刪除如果來自上面的聲明,並簡單地寫在查詢ID ='1'或'2'的數據出現在網頁上,但當我這樣做對於一個特定的ID它不起作用,我使用mysqli_real_escape_string擺脫SQL注入,如果這不是正確的方式來擺脫SQL注入,然後指導我。

+0

否'mysqli_real_escape'不是避免SQL注入的方法。這個[answer](https://stackoverflow.com/a/60496/3072566)有你需要知道的全部 – litelite

+0

謝謝我會試試這個準備好的語句 – johncasio

+1

你的錯誤信息意味着參數'id'不存在於' $ _GET'。你是否用'http://localhost/foo.php?id = X'來調用你的PHP頁面? (其中X是你想要的編號) – litelite

回答

1

您正在檢查$_GET變量id,但您正在根據鏈接傳遞參數item_id

除此之外,您的查詢字符串參數中還有多餘的空格,導致您在URL中看到的奇怪的%20,因此請將其除去。

得到這個工作,您可能需要您的網址更改爲:

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?