首页 > 解决方案 > PHP/PDO:将数据插入外部列

问题描述

我对这一切都很陌生......这是我的代码(我最初是从这里得到的)

<?php

/**
 * Use an HTML form to create a new entry in the
 * users table.
 *
 */


if (isset($_POST['submit'])) {
    require "../config.php";
    require "../common.php";

    try  {
        $connection = new PDO($dsn, $username, $password, $options);
        
        $new_user = array(
            "firstname" => $_POST['firstname'],
            "lastname"  => $_POST['lastname'],
            "email"     => $_POST['email'],
            "age"       => $_POST['age'],
            "location"  => $_POST['location']
        );

        $sql = sprintf(
                "INSERT INTO %s (%s) values (%s)",
                "users",
                implode(", ", array_keys($new_user)),
                ":" . implode(", :", array_keys($new_user))
        );
        
        $statement = $connection->prepare($sql);
        $statement->execute($new_user);
    } catch(PDOException $error) {
        echo $sql . "<br>" . $error->getMessage();
    }
}
?>

<?php require "templates/header.php"; ?>

<?php if (isset($_POST['submit']) && $statement) { ?>
    <blockquote><?php echo $_POST['firstname']; ?> successfully added.</blockquote>
<?php } ?>

<h2>Add a user</h2>

<form method="post">
    <label for="firstname">First Name</label>
    <input type="text" name="firstname" id="firstname">
    <label for="lastname">Last Name</label>
    <input type="text" name="lastname" id="lastname">
    <label for="email">Email Address</label>
    <input type="text" name="email" id="email">
    <label for="age">Age</label>
    <input type="text" name="age" id="age">
    <label for="location">Location</label>
    <input type="text" name="location" id="location">
    <input type="submit" name="submit" value="Submit">
</form>

<a href="index.php">Back to home</a>

<?php require "templates/footer.php"; ?>

这段代码在没有 fk 列的情况下工作得很好。但是在 PHPAdmin 中,我现在将“位置”设置为一个外国列。父表如下所示:

地点

位置 INT (PK)

位置名称 VARCHAR

我在父表中添加了一些位置,但是当我执行上面的代码时,仍然出现此错误:

SQLSTATE [23000]:违反完整性约束:1048 列“位置”不能为空

如何定义外键?我需要一个 SELECT 语句吗?我尝试了几件事,但我就是无法让它发挥作用。我要放弃了,所以我在这里发帖。

非常感谢您的任何回答!

PS:也许任何人都可以推荐任何关于 PHP/PDO/SQL 特定主题的阅读/书籍?

标签: phpmysqlsqlpdo

解决方案


推荐阅读