gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:39:10 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com