php - 使用 mysqli_insert_id 提取最近自动生成的 ID 时,Mysqli/PHP/HTML 重复插入记录
问题描述
我目前有这个代码可以插入到我的收据表中,
$query = "insert into receipt(petname,receipttype)
values('$petname','$receipttype')";
我在其中获取自动生成的 id
$receiptid=mysqli_insert_id($db);
并将其发送到下一页。但是,当插入记录时,还会生成另一个(两个相同的内容但另一个自动生成的 ID 被输入到数据库中)
http://prntscr.com/kpjff6 [具有唯一 ID 的重复字段示例]
if (isset($_POST['cmdedit'])){
$petname = mysqli_real_escape_string($db,$_POST['petname']);
$receipttype = mysqli_real_escape_string($db,$_POST['receipttype']);
$query = "insert into receipt(petname,receipttype)
values('$petname','$receipttype')";
$result = mysqli_query($db,$query);
if (mysqli_query($db,$query)){
$receiptid=mysqli_insert_id($db);
if ($result) {
echo "<font color = 'green' > Receipt sucessfully obtained! Page will auto-redirect to order confirmation page in 5 seconds! </font>";
header( "refresh:5; url=addorderhomepage.php?animalid=".$animalid."&receiptid=".$receiptid);
}else{
echo "<p>Something went wrong! </p>" . mysqli_error($db);
}
}
}
?>
<div class = "topbar">
<h2> Order Receipt </h2>
</div>
<?php
$query = "select *
from catalogue
where animalid= " . $animalid;
$result = mysqli_query($db,$query);
if ($result){
while ($rows = mysqli_fetch_array($result))
{
?>
<form method = "post" action = "" >
<table>
<tr>
<th> Animal ID</th>
<td bgcolor="#FFFFFF"> <input type ="text" name = "txtanimalid" value = "<?php echo $rows[0]; ?>" readonly /> </td>
</tr>
<tr>
<th> Animal Name </th>
<td> <input type ="text" name = "petname" value = "<?php echo $rows[1]; ?>" readonly /> </td>
</tr>
<tr>
<th> Animal Type </th>
<td> <input type ="text" name = "petname" value = "<?php echo $rows[3]; ?>" readonly /> </td>
</tr>
<tr>
<th> Animal Species </th>
<td> <input type ="text" name = "petname" value = "<?php echo $rows[2]; ?>" readonly /> </td>
</tr>
<tr>
<th> Animal Description </th>
<td> <input type ="text" name = "petname" value = "<?php echo $rows[4]; ?>" readonly /> </td>
</tr>
<tr>
<th> Receipt type </th>
<td> <input type ="text" name = "receipttype" value = "printable" readonly /> </td>
</tr>
<tr>
<th> Receipt Date </th>
<td> <input type ="date" name = "orderdate" value="<?php echo date('Y-m-j'); ?>" readonly="readonly" </td>
</tr>
<tr>
<th> <br/><br/> </th>
<td> </td>
</tr>
<tr>
<th> </th>
<td> <input type ="submit" value = "Obtain receipt" name = "cmdedit" /> </td>
</tr>
解决方案
可能会发生重复行,因为您使用相同的数据调用 mysqli_query 两次,第一次将响应存储在 $result var 中,第二次在 if 语句的条件内。
// ... code
$result = mysqli_query($db,$query);
- if (mysqli_query($db,$query)) {
+ if ($result) {
$receiptid = mysqli_insert_id($db);
if ($result) {
// .. rest of the code
推荐阅读
- caching - TLB 索引到底是干什么用的?
- php - 使用 PHP 从 Docx 获取文本而不丢失 HTML 格式
- c# - 从另一个 ID 列表中对弹性搜索结果列表进行排序
- amazon-web-services - 基于标签的 AWS IoT 资源访问不起作用
- selenium - 我如何在 Katalon 自定义关键字下方转换为 Selenium
- yaml - HERE API 地图样式生成器?
- mysql - mysqld_exporter.service 中的 mysqld_exporter 数据源名称
- android - 安卓 SDK 10 . 请选择 Android SDK
- php - php对版本字符串数组进行排序
- sql - 哪个查询在下面列出的 SQL 查询中运行得更快