如何修复PHP不为MySQL插入查询

时间:2019-07-12 16:36:10

标签: php mysql database mysqli

我试图使我的PHP删除包含用户的行等于该人在我的HTML表单上输入的行。我有database.php可以连接到数据库(并且可以工作),还有dlicense.php可以删除该行,但会抛出一个空错误。

database.php

   <?php     
        $servername = "localhost";
$username = "username";
$password = "password";
$dbname = "databasename";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else {
    echo("it works");
}
?>

dlicense.php

<?php


$username = $_POST['username'];

echo "Removing row from $username";

include("database.php");


   $sql = 'DELETE FROM Data WHERE User = $username';

     $retval = mysqli_query( $conn, $sql );


   if(! $retval ) {
      die('Could not delete data: ' . mysqli_error($conn)); 
   }
   echo "Deleted data successfully\n";

   ?>

HTML表单

<form action="dlicense.php" method="POST">
        <label for="username">Enter Username</label>
            <input type="text" name="username" placeholder="Username">
        <button type="submit" class="btn btn1">Submit</button>
        </form>

当我进入database.php时,它显示“有效”,因此我知道它正在连接到数据库。当我填写表格并将其带到dlicense.php时,它仅显示“从testuser1删除行,它无法删除数据:”

1 个答案:

答案 0 :(得分:0)

您应该尝试以下代码:

  <?php


    $username = $_POST['username'];

    echo "Removing row from $username";

    include("database.php");


       $sql = "DELETE FROM Data WHERE User = '$username' ";

         $retval = mysqli_query( $conn, $sql );


       if(! $retval ) {
          die('Could not delete data: ' . mysqli_error($conn)); 
       }
       echo "Deleted data successfully\n";

       ?>

更改位于sql查询中的“”上。

编辑:我刚刚看到CodeBreaker在注释中写了同样的内容。所以也要归功于他