【问题标题】:PDO insert error phpPDO插入错误php
【发布时间】:2012-05-02 15:45:12
【问题描述】:

我正在尝试使用以下脚本将从隐藏表单中获取的值插入到数据库中

 /detect user session
 if (!isset($_SESSION['user']))
 {
//if no session take to login page
header('location:login_main.php');
 }

 //if session detected connect to database using pdo
 $db = getConnection();

 //get holiday infor from hidden form
$user = $_SESSION['user'];
$title = $_POST['title'];
$link = $_POST['link'];
$date = $_POST['date'];
$description = $_POST['description'];

 //insert the values in to favorties table
 $sql = "INSERT INTO saved_holidays (subscriberID, link, pubDate, title, description, dateSaved) 
VALUES (:subscriberID, :link, :pubDate, :title, :description, now())";

$stmt = $db->prepare($sql);
$stmt->bindParam(':subscriberID', $user);
$stmt->bindParam(':link', $link);
$stmt->bindParam(':pubDate',$date);
$stmt->bindParam(':title', $title);
$stmt->bindParam(':description', $description);
$stmt->execute();

echo 'you have sucessfully saved the holiday offer.<meta http-equiv="refresh" content="2; url=index.php" />';

但是当我运行脚本时出现以下错误

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity     constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails     (`unn_w11023553/saved_holidays`, CONSTRAINT `holidays_ibfk_1` FOREIGN KEY (`subscriberID`)     REFERENCES `subscriber` (`email`) ON UPDATE CASCADE)' in [OMISSIS]

谁能告诉我我做错了什么,谢谢

【问题讨论】:

  • 离题:您的脚本中有一个巨大的安全漏洞。 header("Location: ...") 不会退出脚本的执行!

标签: php insert pdo


【解决方案1】:

您的saved_holidays 表中的subscriberID 字段似乎引用了您的subscriber 表中的字段email。

您能给我们展示一些数据样本吗?

我猜您没有在 subscriberID 字段中插入现有订阅者的电子邮件。

【讨论】:

    【解决方案2】:

    这可能不是 PHP 问题:也许您只是违反了foreign key constraint。如果您不了解外键约束,请立即停止编写您的应用程序,并通读我链接的 Wikipedia 文章。

    一些问题:

    • 是您自己设计了数据库,还是只是在使用它?您能否向我们展示您正在向其中插入内容的表的 CREATE TABLE 语句?
    • 您是否通过echo-ing 检查了$user 变量的设置是否正确?
    • 您是否尝试通过硬编码$title、$link、$date 和$description 值来执行准备好的语句?

    题外话:您的脚本中有一个巨大的安全漏洞。 header("Location: ...")doesn't quit the execution of the script!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-28
      • 2016-03-27
      • 2015-04-17
      • 2015-02-28
      • 1970-01-01
      • 2014-08-23
      • 2019-09-21
      • 2012-08-30
      相关资源
      最近更新 更多