如何从数据库中删除记录

时间:2015-10-24 18:39:31

标签: php

请帮助查找以下脚本无效的原因。以下是HTML文档的一部分:

<form>
<table id="prtbl">
<caption id='tblname' name='tblname' readonly value='CRC_Users'></caption>
<tbody>
<tr>
<th>Names</th>
<td><input id='names' name='names' type="text" pattern="[A-Za-z ]{3,12}">     
</td>
</tr>
<tr>
<th>email</th>
<td><input id='email' name='email' type="email" pattern="[A-Za-z0-9@.-_]">
</td>
</tr>
<tr>
<th>Course</th>
<td><input id='course' name='course' type="text" pattern="[A-Za-z ]"></td>
</tr>
<tr>
<th>Project Nu</th>
<td><input id='aktnu' name='aktnu' type="text" pattern="[0-9]{3,12}"></td>
</tr>
</tbody>
</table>
<p><i>Delete record Click:</i>
<input id='deleterec' type="button" value="DELETE"></p>
<p id='feedback'></p>
</form>

该表已存在于服务器数据库中。我可以INSERT,UPDATE表。但我不能删除表中的现有记录。 以下是要删除的脚本:

<script>
$(document).ready(function() {
    $("#deleterec").click(function() {  
        var mydata = {
            tblname : $("#tblname").val(),
            names : $("#names").val()
        };
        $.post("delete_user.php", mydata, function(data) {
            if (data == 1){
                $("#feedback").text('Staff payroll record deleted');
                return;         
            } else {
                $("#feedback").text('Staff payroll record does not exist in  
                your record');
                return;
            }
        });
    }); 
});     
</script>

php脚本如下:

<?php
$servername = "localhost";
$username = "user";
$password = "0007";
$dbname = "CRCSystems";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
$tblname = test_input($_POST["tblname"]);
$names = test_input($_POST["names"]);

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

$sql = "SELECT * FROM $tblname WHERE Names = '$names'";
if (mysqli_query($conn, $sql)) {
    $result = mysqli_query($conn, $sql);
    $row = mysqli_fetch_row($result);
    if ($row) {
        $sql = "DELETE * FROM $tblname WHERE Names = '$names'";
        echo 1;         //record deleted    
    } else {
        echo 0;         //record does not exist 
    }
}
mysqli_free_result($result);
mysqli_close($conn);
?>

现在我进行了故障排除&amp;发现我的PHP脚本至少可以到DELETE行。我改变了:echo 1;回显$ tblname;结果还可以 还要回显$ name,结果还可以。 那么为什么记录没有被删除?即使我得到它已被删除的回复。感谢您的支持。我是初学者。

4 个答案:

答案 0 :(得分:3)

你写过这个

$sql = "DELETE * FROM $tblname WHERE Names = '$names'";

将查询更改为

$sql = "DELETE FROM $tblname WHERE Names = '$names'";

但是你没有执行这个查询。

执行此操作以执行查询。

mysqli_query($conn, $sql)

答案 1 :(得分:2)

删除语法是DELETE FROM NOT DELETE * FROM

$sql = "DELETE FROM $tblname WHERE Names = '$names'";

答案 2 :(得分:0)

method="post"添加到您的表单,因为默认为get。

同样改变:

$sql = "DELETE * FROM $tblname WHERE Names = '$names'";

$sql = "DELETE FROM $tblname WHERE Names = '$names'";

答案 3 :(得分:0)

我认为你没有向DB发送DELETE查询。

删除查询语法应为DELETE FROM