gpt4 book ai didi

php - MySQL用PHP删除行

转载 作者:太空宇宙 更新时间:2023-11-03 10:51:22 28 4
gpt4 key购买 nike

我在从我的 mySQL 数据库中的一个表中删除一行时遇到问题。下面您可以看到我正在使用的代码(这是 php 文件,它从表单调用 SQL 查询):

                   <?php 
echo '
<form style="padding-left:30px; padding-bottom:40px; padding-top:10px; clear:both;" action="deletingcontactgroups.php">
<label><strong>Please Select A Group to Delete!</strong></label>
<select name="dropdown" style="float:left;">
<option value="">Select a Contact Group:</option>';

$con=mysqli_connect("localhost","username","password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM ContactsGroup");


while($row = mysqli_fetch_array($result)) {
echo '<option value="' . $row["GroupName"] . '">' . $row["GroupName"] . '</option>';
echo "<br>";
}
echo '<input type="submit" style="clear:both; float:left; margin-left: 300px;">';
echo '</form>';

mysqli_close($con);

?>

这是 deletingcontactgroups.php 文件中的数据:

<?php
$con=mysqli_connect("localhost","username","password","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$groupname = mysqli_real_escape_string($con, $_POST['dropdown']);
$sql = "DELETE FROM `bulletproofaccounting`.`ContactsGroup` WHERE `ContactsGroup`.`GroupName` = '" . $groupname . "' LIMIT 1;";
mysqli_query($sql);

echo "1 record has been deleted successully!!!";

mysqli_close($con);
?>

我查看了各种教程,但没有任何帮助。任何帮助将不胜感激!

编辑!!!我对打字错误感到非常抱歉,但引号实际上是在连接变量 $sql 时放置的。抱歉给您带来麻烦。

最佳答案

将您的删除语句更改为此

  $sql = sprintf("delete from contactsgroup where groupname = '%s'", $groupname);

除此之外,上面的代码非常糟糕,因为它容易受到 SQL 注入(inject)攻击。永远不要将 SQL 命令字符串连接起来。改用参数化查询:

$stmt = $con->prepare('delete from contactsgroup where groupname = ?');
$stmt->bind_param('s', $groupname);
$stmt->execute();

关于php - MySQL用PHP删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24713486/

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