我有两个表,如果可能的话,我想同时update
和via 1 query
。我有一个customer table
,其中primary key of cusomerid
被设置为自动递增,而complaints table
中customerid
被设置为foreign key.
我想从客户表中删除,简单地说,当我删除该客户时,它也应该从投诉表中删除。希望这是有道理的。有人能解释一下如何实现我的上述两个目标吗?
<?php
include("functions.inc.php");
display_header("Delete a record");
?>
<?php
require_once("dbconnect.inc.php");
?>
<!--displays array easier to read-->
<?php //echo '<pre>';?>
<div id="container">
<header><?php include("header.inc.php");?></header>
<nav><?php include("navbar.inc.php");?></nav>
<?php include("sidebar.inc.php");?>
<p>
<img src="images/relationsimage.PNG"/>
<form action="delete.php" method="post">
<?php
$query = "SELECT * FROM customer";
$resultset = $conn->query($query);
while ($row = $resultset->fetch())
{
echo "<p>";
echo "<input type='checkbox' name='customer[]' id='customer".$row['customerid']."' value='".$row['customerid']."'>";
echo "<label for='customer".$row['customerid']."'>".$row['title']." ".$row['forename']." ".$row['surname']." ".$row['roadname']." ".$row['town']." ".$row['county']." ".$row['postcode']." ".$row['phonenumber']." ".$row['paymentmethod']."</label>";
echo "</p>";
}
?>
<input type="submit" value="delete these sales leads">
</form>
<?php
if (!isset($_POST['customer']))
{
echo "";
exit;
}
$query="DELETE FROM customer WHERE customerid=:customerid";
$pr_stmt=$conn->prepare($query);
$affected_rows=0;
foreach($_POST['customer'] as $cusid)
{
$pr_stmt->bindValue(':customerid',$cusid);
$affected_rows += $pr_stmt->execute();
}
echo "Deleted ".$affected_rows." customer from customers table";
$conn=NULL; //close the connection
?>
</p>
<footer><?php include("footer.inc.php");?></footer>
</div>
</body>
</html>
您只需要让外键有一个on delete属性集,请参阅本教程,它将向您展示如何设置on delete,以便相应表中的行也被删除:http://www.mysqltutorial.org/mysql-on-delete-cascade/