dsideal2015 2011-03-26 08:11
浏览 12
已采纳

如果声明不起作用

I have 2 sql queries in my code where the second one is wrapped around an if statement which should only execute if a certain post value exists.

But I still get the following error message:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (database1.table2, CONSTRAINT fk_referals_users1 FOREIGN KEY (users_id) REFERENCES users (id) ON DELETE NO ACTION ON UPDATE NO ACTION)

Clearly that if statement is not working, if it was, it would not get to the second sql query.

Here is the problem section of the script:

$STH = $DBH -> prepare( "insert into database1.table1 (display_name, email, password) values ( :display_name, :email, :password )" );

$STH -> bindParam( ':display_name', $_POST['display_name'], PDO::PARAM_STR, 100 );
$STH -> bindParam( ':email', $_POST['email'], PDO::PARAM_STR, 100 );
$STH -> bindParam( ':password', $_POST['password'], PDO::PARAM_STR, 100 );

$STH -> execute();

if( isset( $_POST['referer'] ) or ( $_POST['referer'] != null ) or ( $_POST['referer'] != "" ) ) {
    $STH = $DBH -> prepare( "insert into database1.table2 ( username, status, users_id ) values ( :username, :status, :users_id )" );

    $strStatus = 1;

    $STH -> bindParam( ':username', $_POST['display_name'], PDO::PARAM_STR, 100 );
    $STH -> bindParam( ':status', $strStatus, PDO::PARAM_INT, 1 );
    $STH -> bindParam( ':users_id', $_POST['referer'], PDO::PARAM_INT, 1 );

    $STH -> execute();
}
  • 写回答

3条回答 默认 最新

  • dongqianwei6664 2011-03-26 08:16
    关注

    The IF statement checks whether a certain POST value is set. Your foreign key constraint checks whether the value in the POST field is present in the users table. These two conditions are not related. The POST field can be set with a value that is not present in the users table. You should check whether the value is present in the users table (do a COUNT maybe?) before trying to insert (this depends on your setup, of course)

    Also, you should use empty() for your IF condition as isset() will trip your condition to TRUE even if the value is empty. Better to use

    if (!empty($_POST['referer'])) {
       //your code here
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系