从PHP的下拉菜单中删除MySQL数据库选择

时间:2018-03-25 01:38:36

标签: php html mysql

我目前正在为我们的学校信息中心撰写知识库。目前我正在为主持人制作一个删除文章的页面。该页面从数据库中的“articles”表中获取所有数据,以在下拉菜单中显示它。然后,用户可以选择任何一个并按删除。我打算说按钮获取所选ID并将其从数据库中删除。但是它不会删除。

代码:

<?php
session_start();
echo 'Select an article to delete, '.$_SESSION['username']. '<br>';
include 'index.php';

    {
        if(isset($_POST['Delete'])){
            $delete = 'DELETE FROM articles WHERE articleID IN (' . implode(',', $_POST['articles']) . ')';
            if(mysqli_query($link, $delete))
        {
            echo '<script language="javascript">';
            echo 'alert("Article was deleted!")';
            echo '</script>';
        }
        else
        {
            echo 'ERROR: Could not delete article';
        }
    }
}


?>


<form method="post" action="deleteArticles.php">
<select name="articles" multiple="multiple">

    <?php
    $sql=mysqli_query($link,"SELECT * FROM articles ORDER BY title");
    while ($row = mysqli_fetch_assoc($sql))
    {
        echo '<option value="' . $row['articleID'] . '">' . $row['title'] . '</option>';
    }
    ?>

</select>
<input type="submit" value="Delete" name="Delete" />
</form>

1 个答案:

答案 0 :(得分:0)

您错过了关闭打开的选择标记。您也没有添加多个属性以允许多个选择。

<select name="articles" multiple="multiple">

    <?php
    $sql=mysqli_query($link,"SELECT * FROM articles ORDER BY title");
    while ($row = mysqli_fetch_assoc($sql))
    {
        echo '<option value="' . $row['articleID'] . '">' . $row['title'] . '</option>';
    }
    ?>

</select>

删除了不需要的{}包装。

而且:

<?php
session_start();
echo 'Select an article to delete, '.$_SESSION['username']. '<br>';
include 'index.php';
{

if(isset($_POST['Delete'])){
    $delete = 'DELETE FROM articles WHERE articleID IN (' . implode(',', $_POST['articles']) . ')';
    if(mysqli_query($link, $delete))
    {
        echo '<script language="javascript">';
        echo 'alert("Article was deleted!")';
        echo '</script>';
    }
    else
    {
        echo 'ERROR: Could not delete article';
    }
}
}


?>

<?php
session_start();
echo 'Select an article to delete, '.$_SESSION['username']. '<br>';
include 'index.php';

if(isset($_POST['Delete'])){
    $delete = 'DELETE FROM articles WHERE articleID IN (' . implode(',', $_POST['articles']) . ')';
    if(mysqli_query($link, $delete))
    {
        echo '<script language="javascript">';
        echo 'alert("Article was deleted!")';
        echo '</script>';
    }
    else
    {
        echo 'ERROR: Could not delete article';
    }
}
?>    

由于是多项选择,请将选择名称更改为文章[]

<强>像:

<select name="articles[]" multiple="multiple">