使用php函数

时间:2018-04-09 12:20:16

标签: php html mysql

我创建了这个简单的函数,可以根据输入的用户名从数据库中删除一行。但是,即使输入的用户名是正确的,我也无法将行实际删除。有没有人有任何建议,为什么这不起作用? (我是php的新手,如果注射和/或布局/编码存在问题,很抱歉)

<?php
    $uname = "xxxx";
    $password = "xxxx";
    $host = "xxxx";
    $db = $uname;
    $connection = mysqli_connect($host, $uname, $password, $db);
    if (mysqli_connect_error()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    } else {
        echo "<h1> Delete User </h1>";
        if (isset($_POST["delSubmit"])) {
            if ((!empty($_POST["username"]))) {

                $query = "DELETE FROM login WHERE username = " . $_POST['username'] . ";";
                $result = mysqli_query($connection, $query);

                if ($result == false) {
                    echo "<p> Deleting user " . $_POST["username"] . " failed </p>";
                } else {
                    echo "<p> The user \"" . $_POST["username"] . "\" has been deleted";
                }
            }
        }
    }

?>
    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    <form id="delForm" name="delForm" action="?" method="post">
        <div>
            <label for="delFormID">Please insert username to delete</label>
            <input id="delFormID" name="username">
        </div>
        <div>
            <input id="delSubmit" name="delSubmit" value="Delete User" type="submit">
        </div>
    </form>
    </body>
    </html>
<?php
    mysqli_close($connection);
?>

3 个答案:

答案 0 :(得分:3)

使用如下的预备声明:

$stmt = $mysqli->prepare("DELETE FROM login WHERE username = ?");
$stmt->bind_param("i", $_POST["username"]);
$stmt->execute();

答案 1 :(得分:-1)

解决您的问题:

正如其他人所说,改变

$query = "DELETE FROM login WHERE username = " . $_POST['username'] . ";";

$query = "DELETE FROM login WHERE username = '" . $_POST['username'] . "';";

在MySQL中,字符串必须被"'包围(实际上,我知道每个SQL实现)。

补充说明

1)如果字符串只包含一个语句,您可以在字符串末尾省略;。这意味着您可以将上面的行更改为

$query = "DELETE FROM login WHERE username = '" . $_POST['username'] . "'";

2)永远不会将任意数据发送到任何SQL服务器,因为这会使您的代码容易出现SQL注入。相反,使用预准备语句或存储过程(在后一种情况下,确保您的SP代码不再从SP的参数构造文字SQL字符串,否则您将再次遇到可能的SQL注入。)

答案 2 :(得分:-2)

定义action =“”而不是action =“?”。

将查询更改为

$ query =“DELETE FROM login WHERE username ='”。$ _ POST ['username']。“'”;