如何使用PHP从SQL中删除数据?

时间:2017-03-10 17:02:25

标签: php sql

这是我用于显示sql数据的PHP代码

<?php 

$con=mysqli_connect("localhost","root","password","registration"); 
if (mysqli_connect_errno()) 
{ 
    die("Failed to connect to MySQL: " . mysqli_connect_error()); 
}

$query = "SELECT * FROM goal WHERE userid = $_SESSION[userid]";
$result = mysqli_query($con, $query);

if($result == false) {
    die("Query failed: ".mysqli_error($con).PHP_EOL.$query);
}

while($row = mysqli_fetch_assoc($result))  
{ 

echo "<div><br><br></div>";
echo "<p style='font-size: 16px'>"."<strong>".'Weight to lose: '.$row['weightlost']."</strong>"."</p>\n";
echo "<p style='font-size: 16px'>"."<strong>".'Weight unit: '.$row['weightunit']."</strong>"."</p>\n";
echo "<p style='font-size: 16px'>"."<strong>".'Date of when to lose the weight by: '.$row['whenby']."</strong>"."</p>\n";
echo "</div>";
echo "<form method='POST'>"."<input type='submit' value='Delete'>"."</form>\n";

} 
mysqli_close($con);

?>

我添加了删除按钮。我正在尝试允许我的用户点击此删除按钮,以便他们可以删除他们为自己设置的特定目标。

在sql中,一个目标包括“体重减轻”,“体重单位”和“何时减肥的数据”。

2 个答案:

答案 0 :(得分:0)

如果您的数据库中有一个ID字段(您应该这样做),只需添加隐藏了ID的输入类型即可。

while($row = mysqli_fetch_assoc($result))  
{ 

echo "<div><br><br></div>";
echo "<p style='font-size: 16px'>"."<strong>".'Weight to lose: '.$row['weightlost']."</strong>"."</p>\n";
echo "<p style='font-size: 16px'>"."<strong>".'Weight unit: '.$row['weightunit']."</strong>"."</p>\n";
echo "<p style='font-size: 16px'>"."<strong>".'Date of when to lose the weight by: '.$row['whenby']."</strong>"."</p>\n";
echo "</div>";
echo "<form action='delete.php' method='POST'><input type='hidden' name='id' value='{$row['id']}'><input type='submit' value='Delete'></form>";

} 

然后在delete.php

<?php 

$con=mysqli_connect("localhost","root","password","registration"); 
if (mysqli_connect_errno()) 
{ 
    die("Failed to connect to MySQL: " . mysqli_connect_error()); 
}

$id=intval($_POST['id']);
$query = "delete from goal WHERE userid = $_SESSION[userid] and id='$id'";
$result = mysqli_query($con, $query);

if($result == false) {
    die("Query failed: ".mysqli_error($con).PHP_EOL.$query);
}
?>

答案 1 :(得分:0)

为了确保您正确跟踪项目,建议您使用auto_increment id字段。您可以通过以下查询创建一个:

CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)

请参阅https://www.w3schools.com/sql/sql_autoincrement.asp寻求帮助。

然后,我会通过隐藏字段将id添加到页面中(因此用户看不到id,他/她不需要看到)。

echo "<form action='post'><input name='id' type='hidden' value='" . $row['id'] . "'>"."<input type='submit' value='Delete'></form>";

PHP代码非常相似,但您必须将其更改为删除sql查询:

DELETE FROM table_name WHERE [condition];

Here's a reference.