PHP:删除||确认删除

时间:2013-11-19 19:22:18

标签: php mysql database server-side delete-row

我遇到了问题。

我正在创建一个脚本,允许某人通过它的主ID选择记录,然后通过单击确认按钮删除该行。

这是具有以下形式的代码: “confirmdelete.php”

<?php
include("dbinfo.php");
$sel_record = $_POST[sel_record];

//SQL statement to select info where the ID is the same as what was just passed in
$sql = "SELECT * FROM contacts WHERE id = '$sel_record'";

//execute SELECT statement to get the result
$result = mysql_query($sql, $db) or die (mysql_error());//search dat db
if (!$result){// if a problem
    echo 'something has gone wrong!';
}
else{
    //loop through and get dem records
    while($record = mysql_fetch_array($result)){
        //assign values of fields to var names
        $id = $record['ID'];
        $email = $record['email'];
        $first = $record['first'];
        $last = $record['last'];
        $status = $record['status'];
        $image = $record['image'];

        $filename = "images/$image";

    }

$pageTitle = "Delete a Monkey";
include('header.php');

echo <<<HERE
Are you sure you want to delete this record?<br/>
It will be permanently removed:</br>
<img src="$filename" />
<ul>
<li>ID: $id</li>
<li>Name: $first $last</li>
<li>E-mail: $email</li>
<li>Status: $status</li>
</ul>
<p><br/>
<form method="post" action="reallydelete.php">
<input type="hidden" name="id" value="$id">
<input type="submit" name="reallydelete" value="really truly delete"/>
<input type="button" name="cancel" value="cancel" onClick="location.href='index.php'" /></a>
</p></form>
HERE;
}//close else
//when button is clicked takes user back to index
?>

,这是它调用的reallydelete.php代码

<?php
include ("dbinfo.php");

$id = $_POST[id];//get value from confirmdelete.php and assign to ID
$sql = "SELECT * FROM contacts WHERE id = '$id'";//where primary key is equal to $id (or what was passed in)

$result=mysql_query($sql) or die (mysql_error());
//get values from DB and display from db before deleting it
while ($row=mysql_fetch_array($result)){
    $id = $row["id"];
    $email = $row["email"];
    $first= $row["first"];
    $last = $row["last"];
    $status = $row["status"];

    include ("header.php");
    //displays here
    echo "<p>$id, $first, $last, $email, $status has been deleted permanently</p>";
}

$sql="DELETE FROM contacts WHERE id = '$id'";
//actually deletes
$result = mysql_query($sql) or die (mysql_error());
?>

问题是它实际上从未真正进入“while”循环 连接绝对没问题。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

1:$_POST[id];不应该是$_POST['id']; var_dump() 更改后再试一次。 如果它仍然不起作用,请尝试{{1}}到您的结果,看它是否返回任何行。 如果它是空的或没有行,那么它是无效的是绝对正常的。 并确保id正确到达你的php页面。

答案 1 :(得分:0)

好的,您刚刚开始,请注意这些语法,然后尝试切换到PDOmysqli_*而不是mysql ..

代码中的两个主要语法错误:

参数必须写在''

E.g: $_POST['id']而非$_POST[id]

其次,您必须使用连接点来回显变量:

E.g:

echo "Nane:".$nane;echo $name;但不是echo "Name: $name";

同样在mysql_query E.g:

$sql = "SELECT * FROM table_name WHERE id="'.$id.'";

我希望你能得到它......关心这些东西......