php - 如何从html删除按钮中删除mysql数据?

标签 php html mysql database

我有一个项目列表,每个项目都有一个删除按钮,但是当我按下它时什么也没有发生。数据库已连接,因为它显示表中的项目,但我不知道为什么删除按钮不起作用。如果有人看到错误,请告诉我。非常感谢。另外,这是我的第一个网站,所以我的代码现在很困惑。

Note: I do close the database so that's not a problem.

user.php:

<?php
$user_id = '999';
$host="127.0.0.1";
$port=3306;
$socket="";
$user="root";
$password="root";
$dbname="peas";
 $db = new mysqli($host, $user, $password, $dbname, $port, $socket) or die ('Could not connect to the database server' . mysqli_connect_error());
?>
//continued 

<div style: "height:1000px; class="col-md-3" id="ingredients">
    <ul class="list-group" style="max-height:900px; overflow-y:auto; overflow-x: hidden">
        <?php
            $query = "SELECT  ingredient_name FROM Ingredient";
            $result = mysqli_query($db, $query);

            if(mysqli_num_rows($result) > 0) {
               while($row = mysqli_fetch_array($result)){   ?>
                   <li style="text-align: left; padding:10px" 
                    class="list-group-item">
                            <form action="user_functions.php" method="post">
                                <?php echo $row['ingredient_name'];?>
                                <input type="hidden" name="ingredient_name" value= "<?php $row['$ingredient_name']; ?>">
                                <button type="button" name="delete" style="float:right; border:none;">&times;</button>
                            </form>
                    </li>
            <?php }
            mysqli_free_result($result);
            } else{
                echo "<li>"."Pantry is Empty!"."</li>";
            }
        ?>
    </ul>
</div>

user_functions.php:

<?php
    if(isset($_POST['delete'])){
        $ingredient_name=$_POST['ingredient_name'];
        $sql="DELETE FROM ingredient WHERE ingredient_name=$ingredient_name";
        $result = mysqli_query($db, $sql);
    }
?>

最佳答案

您必须将 HTML 代码更改为:

<form action="user_functions.php" method="post">
    <?php echo $row['ingredient_name'];?>
    <input type="hidden" name="ingredient_name" value="<?php echo $row['$ingredient_name']; ?>">
    <button type="submit" name="delete" style="float:right; border:none;">&times</button>
</form>

并将 user_functions.php 编辑为:

<?php
    if(!empty($_POST['submit']) && isset($_POST['ingredient_name'])){
        $stmt = $db->prepare("DELETE FROM ingredient WHERE ingredient_name=?");
        $stmt->bind_param('s', $_POST['ingredient_name']);
        $stmt->execute();
    }
?>

关于php - 如何从html删除按钮中删除mysql数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59113323/

相关文章:

PHP SQL 更新在提交时未更新正确的行

php - 是否存在可以在我的服务器上托管的在线 IDE?

php - 如何区分命令行和 Web 服务器调用?

html - 谷歌如何确定帖子的发布日期?

html - css img tint 仅在图像不可见时有效(图像覆盖色调?)

html - 如何强制 span 在 CSS 中使用父字体系列

php - 让 Zend Framework 2 Memcached 工作

php - 查询3张表,不重复

php - 在 update mysql 命令中使用别名的问题

mysql - 将 MySQL 表更新为构造的双聚合,这取决于表本身