2016-12-16 42 views
0

我寫了這段代碼,我確信代碼和服務器中的所有東西都是正確的,但它不起作用! 有什麼問題?在php中的數據庫

<?php 
    $id = isset($_POST["id"]); 
    $decrease = isset($_POST["dis"]); 
    $conn = mysqli_connect('localhost', 'root',''); 
    $select = mysqli_select_db($conn, "test"); 
    if ($decrease=='10%') 
    $q1 = 'update book set Price=Price-Price * 0.1 where ID="$id";'; 
    else 
    $q1 = 'update book set Price=Price-Price* 0.3 where ID="$id";'; 
    $b = mysqli_query($conn, $q1); 
    $query = "select * from book where ID = '$id';"; 
    $res = mysqli_query($conn, $query); 
    $r = mysqli_fetch_row($res); 

    print("<table border='1'><tr><td>ID</td><td>Name</td><td>Price</td>    </tr>"); 
    echo '<td>'.$r[0].'</td><td>'.$r[1].'</td><td>'.$r[2].'</td>'; 
?> 
+2

不'$ id = isset($ _ POST [「id」]) ;'而是'$ id =(integer)$ _POST [「id」];'這樣(1)你不會在'$ id'中得到'isset()'的布爾結果,你防止SQL注入。 – WEBjuju

+0

注意:未定義的索引:C:\ xampp \ htdocs \ Works中的id \第2行的新文本Document.php –

+1

並且在您的查詢中將''$ id「'更改爲'」'。$ id。'「' 。關於'Notice:Undefined index'的問題是表單發佈,如果沒有,錯誤是正確的。因爲當沒有發佈時,沒有'$ _POST ['id']'。請學習在php編碼和表單處理的基礎知識# – JustOnUnderMillions

回答

0

你分配isset值的變量,這意味着它將永遠是真還是假。相反,使用isset在if語句中,然後運行一切它下面:在報價

<?php 
if(isset($_POST["id"]) && isset($_POST["dis"])) { 
    $id = $_POST["id"]; 
    $decrease = $_POST["dis"]; 
    $conn = mysqli_connect('localhost', 'root',''); 
    $select = mysqli_select_db($conn, "test"); 
    if ($decrease=='10%') 
     $q1 = "update book set Price=Price-Price * 0.1 where ID='$id'"; 
    else 
     $q1 = "update book set Price=Price-Price* 0.3 where ID='$id'"; 
    $b = mysqli_query($conn, $q1); 

    $query = "select * from book where ID = '$id'"; 
    $res = mysqli_query($conn, $query); 
    $r = mysqli_fetch_row($res); 

    print("<table border='1'><tr><td>ID</td><td>Name</td><td>Price</td>    </tr>"); 
    echo '<td>'.$r[0].'</td><td>'.$r[1].'</td><td>'.$r[2].'</td>'; 
} else { 
    // Do something else if it hasn't been posted 
} 
?> 

講究的變化在這裏。變量不會用單引號字符串處理,因此您需要在更新行上更改爲雙引號字符串。但是,最好使用帶有bind_param的prepared statements來代替,因此您不必擔心引用或SQL注入。

0
  1. 第一個問題

    $id = isset($_POST["id"]); 
    

isset()功能將根據數組元素的可用性返回true或false。

正確的方法將是

if(isset($_POST["id"])) 
{ 
    $id = $_POST["id"]; 
} 
  • 問題

    $conn = mysqli_connect('localhost', 'root',''); 
    $select = mysqli_select_db($conn, "test"); 
    
  • 爲mysqli_connect

    正確的語法是:

    $link = mysqli_connect("localhost", "root", "", "test");