php - 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 特定主题的阅读/书籍?
解决方案
推荐阅读
- swift - 是否可以禁用一半的步进器
- javascript - javascript和jquery中的鼠标移动滞后
- php - 禁止通过 PHP Curl 在 Dynamics 365 AX 上调用方法
- r - 是否有 R 函数可以将回归线和回归方程添加到 ggplot
- php - 我正在尝试使用 MySql 和 php 从数据库中回显数据
- java - 如何将项目添加到列表中
在 Android 上选中复选框时 - java - 带有密钥的 GSON json 对象数组的通用解决方案
- flutter - 如何在 Flutter Web 中添加自定义字体?
- django-rest-framework - Django Rest 框架关系序列化
- c++ - C++中cbrt()的优化