0

我有一个脚本,其中将 2 个通知插入到数据库表中,但它只添加第一个注释而不是第二个。我试过交换它们,但它仍然只发布 2 个中的第一个。这是我的代码:

<?php
$type = "---";
$title = "---";
$note1 = "Note 1";
$note2 = "Note 2";
?>
<?php
if($business1 !== ""){
    $insert_note1_sql = "INSERT INTO notes (id, recipient, type, title, post, message, date) VALUES('$id', 'Business 1', '$type', '$title', '$event', '$note1', '$time')";
    $insert_note1_res = mysqli_query($con, $insert_note1_sql);
};
?>
<?php
if($business2 !== ""){
    $insert_note2_sql = "INSERT INTO notes (id, recipient, type, title, post, message, date) VALUES('$id', 'Business 2', '$type', '$title', '$event', '$note2', '$time')";
    $insert_note2_res = mysqli_query($con, $insert_note2_sql);
};
?>

谁能看到为什么第二个不发布(他们都是!==“”)?

4

3 回答 3

2

id字段可能是主键字段,并且由于您$id在两个查询中都使用相同的插入查询,因此您会遇到重复的键违规。

您应该检查返回值是否失败,例如

$insert_note1_res = mysqli_query(...);
if ($insert_note1_res === FALSE) {
   die(mysqli_error());
}
于 2013-09-24T17:21:14.633 回答
1

尝试在两个插入查询中使用此语句

$insert_note1_sql = "INSERT INTO notes (recipient, type, title, post, message, date) VALUES('Business 1', '$type', '$title', '$event', '$note1', '$time')";

然后 $insert_note2_sql = "INSERT INTO notes (recipient, type, title, post, message, date) VALUES('Business 2', '$type', '$title', '$event', '$note2', '$time')"; 看看它是否工作正常......如果它现在工作正常那么这意味着问题出在主键上,即你的 ID

于 2013-09-24T17:33:28.810 回答
0

IF语句不使用;

if($business2 !== ""){
    $insert_note2_sql = "INSERT INTO notes (id, recipient, type, title, post, message, date) VALUES('$id', 'Business 2', '$type', '$title', '$event', '$note2', '$time')";
    $insert_note2_res = mysqli_query($con, $insert_note2_sql);
}; // <--------- ISSUE

合适的方式

<?php
$type = "---";
$title = "---";
$note1 = "Note 1";
$note2 = "Note 2";

echo $business1;

if($business1 !== ""){
    $insert_note1_sql = "INSERT INTO notes (id, recipient, type, title, post, message, date) VALUES('$id', 'Business 1', '$type', '$title', '$event', '$note1', '$time')";
    $insert_note1_res = mysqli_query($con, $insert_note1_sql);
}

echo $business2;

if($business2 !== ""){
    $insert_note2_sql = "INSERT INTO notes (id, recipient, type, title, post, message, date) VALUES('$id', 'Business 2', '$type', '$title', '$event', '$note2', '$time')";
    $insert_note2_res = mysqli_query($con, $insert_note2_sql);
}
?>
于 2013-09-24T17:20:44.743 回答