2016-12-16 46 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");