我是php和sql领域的新手。当我点击remove链接(或按钮)时,我正在尝试从Persons表中删除身份。有人能告诉我我做错了什么吗?
这是我的php代码:
<?php
$db = new DB();
$cg_id = $_SESSION['cg_id'];
$cg_address_id = $_SESSION['cg_address_id'];
$sql ="SELECT f_name, phone, c.id as idc
FROM contacts as c
WHERE c.cg_id = '$cg_id'";
$result = $db->mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<article class='contactArea'>";
echo "<a href='contacts2.php?del=".$row["idc"]."' class='deleteContact' name='remove' value='remove'>Remove</a></article>";
if(isset($_POST['idc'])){
$idco = $_POST['idc'];
$removeQuery = "DELETE FROM contacts as c WHERE id=".$idco." ";
$resultt = mysql_query($removeQuery);
if($resultt) {
header('Location: '.$_SERVER['REQUEST_URI']);
}
echo "<script>window.location.reload(true);</script>";
}
}
}else {
echo "Please edit senior profile for monitoring!";
}
?>发布于 2015-07-28 22:31:59
试试这个(显然将"localhost“、"dbuser”、"dbpassword“和"database_name”替换为您的mysql服务器和数据库的详细信息):
<?php
$db = new mysqli("localhost","dbuser","dbpassword","database_name");
$cg_id = $_SESSION['cg_id'];
$cg_address_id = $_SESSION['cg_address_id'];
// I've moved the deletion code to BEFORE the select query, otherwise the
// query will be shown including the to-be-deleted data and it is then deleted after it is displayed
if(isset($_GET["del"])){ // <--- this was $_POST["del"] which would have been unset
$idc = $_GET["del"];
if($db->query("DELETE FROM contacts WHERE id=$idc")){
echo "deleted";
} else {
echo "fail";
}
}
$sql ="SELECT photo, f_name, phone, street, street_num, city, l_name, c.id as idc FROM contacts as c, address as a WHERE c.cg_id = '$cg_id' and a.id = c.address_id";
$result = $db->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<article class='contactArea'>";
echo "<article class='contact5 lior'>";
echo "<img class='CSImage' src='" .$row["photo"]."'>";
echo "<section class='generalFormTextW nameCPosition'> " .$row["f_name"]." ".$row["l_name"]."<br></section>";
echo "<section class='generalFormTextW phoneCPosition'> " .$row["phone"]."<br></section>";
echo "<section class='generalFormTextB addressCPosition'>".$row["city"].", <br> ".$row["street"]." ".$row["street_num"]. "<br></section>";
echo "<a href='contacts2.php?del=".$row["idc"]."' class='deleteContact' name='remove' value='remove'>Remove</a></article></article>";
}
}
?>请注意,我正在更改您使用mysqli的方式,以便您直接使用它,而不是像我在其他地方看到的那样,将其作为DB对象的成员使用-在我看来,您实际上并没有打开数据库连接(尽管您只是因为它显示了您的密码而没有包含它?)
**编辑:我已将$_POST" del“更改为$_GET"del”--因为您在url ("contacts2.php?del=")中设置了del,所以这将是GET not POST。
**EDIT:我已经移动了删除代码,所以它修复了你必须刷新页面才能看到删除了记录的数据的问题-以前信息是显示然后删除的,我们想要删除然后显示。
https://stackoverflow.com/questions/31674231
复制相似问题