PHP脚本没有执行第二个命令

时间:2013-09-24 17:18:07

标签: php if-statement insert

我有一个脚本,其中将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);
};
?>

任何人都可以看到为什么第二个没有张贴(他们俩都是!==“”)?

3 个答案:

答案 0 :(得分:2)

id字段可能是主键字段,并且由于您在两个查询中都使用相同的$id进行插入,因此您将获得重复的密钥违规。

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

$insert_note1_res = mysqli_query(...);
if ($insert_note1_res === FALSE) {
   die(mysqli_error());
}

答案 1 :(得分: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

答案 2 :(得分: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);
}
?>