删除div和sql记录

时间:2016-03-19 20:02:38

标签: php

我为我的网站制作了邮件系统,这是我用来在其个人资料中显示不同用户邮件的代码。这将从数据库中获取消息并将其显示在div中的页面中(新div中的每条消息)。我添加了“删除消息”'用户删除某些邮件,但我不知道它是如何工作的。我希望它删除div和数据库记录。我是PHP的新手,对我来说这是非常复杂的。

<div style='height: auto; margin-top: 0px; padding: 50px;' id='content'>
<?php   
    session_start();
    if (!isset($_SESSION['name'])) {
        header('Location:vhod.php');
        exit;
    }

    $pageTitle = 'СЪОБЩЕНИЯ';
    include 'includes/header.html'; 

    $email = $_SESSION['email'];
    $name = $_SESSION['name'];

    include 'php/db_connect.php';

    $msgs = '';
    $query = "SELECT * FROM `msg` WHERE `to` = '$name'";
    $result = mysqli_query($conn, $query);

    if (mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_assoc($result)) {
            echo "<div class='msg_box'>" . "<strong>>> Дата и час: </strong>" . $row["timestamp"] . "<br>" . " <strong>>> От: </strong>" . "<i>" . $row["sender"] . "</i>" . "<br>" . " <strong>>> Тема: </strong>" . "<i>" . $row["subject"] . "</i>" . "<br>" . "<strong>>> Съобщение: </strong>" . "<i>" . $row["msg"] . "</i>" . "<br>" ."<br>" ."<strong><a href='' >DELETE MESSAGE</a></strong>" . "</div>" . "<br>" . "<br>" . "<br>" ;
        }
    } else {
        echo "<h2>Нямате съобщения :(</h2>";
    }
?>

</div>

1 个答案:

答案 0 :(得分:0)

要从数据库中删除项目,您可以引用其中一个列值。最好使用记录的ID值。因此,您需要在“删除邮件”链接中传递每封邮件的ID。

然后你必须为“DELETE MESSAGE”按钮创建一个单独的脚本函数,该函数将消息的id作为输入。

试试这段代码:

<div style='height: auto; margin-top: 0px; padding: 50px;' id='content'>
<?php   
session_start();
if (!isset($_SESSION['name'])) {
    header('Location:vhod.php');
    exit;
}

$pageTitle = 'СЪОБЩЕНИЯ';
include 'includes/header.html'; 

$email = $_SESSION['email'];
$name = $_SESSION['name'];

include 'php/db_connect.php';

$msgs = '';
$query = "SELECT * FROM `msg` WHERE `to` = '$name'";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) > 0) {
    while($row = mysqli_fetch_assoc($result)) {
        echo "<div class='msg_box'>" . 
             "<strong>>> Дата и час: </strong>" . $row["timestamp"] . "<br>" . 
             " <strong>>> От: </strong>" . "<i>" . $row["sender"] . "</i>" . "<br>" . 
             " <strong>>> Тема: </strong>" . "<i>" . $row["subject"] . "</i>" . "<br>" . 
             "<strong>>> Съобщение: </strong>" . "<i>" . $row["msg"] . "</i>" . "<br>" ."<br>" .
             "<strong><a href='deletemsg.php?id=".$row["id"]."' >DELETE MESSAGE</a></strong>" . "</div>" . "<br>" . "<br>" . "<br>" ;
    }
} else {
    echo "<h2>Нямате съобщения :(</h2>";
}
?>

</div>

deletemsg.php:

<?php
$msgsid = $_GET("id");
include 'php/db_connect.php';

//create connection if you need it

$query = "DELETE FROM  `msg` WHERE `id` = '$msgsid'";
$result = mysqli_query($conn, $query);

比刷新页面。

注意在查询中替换$row["id"]id,其中db的列名称包含行ID(如果不同)