how to pass a null value to a foreign key field?(如何将空值传递给外键字段?)
问题描述
我有两张桌子:
大学
:
university_id(p.k) | university_name
和用户
:
uid | name | university_id(f.k)
如何在用户表中保持university_id
NULL?
How to keep university_id
NULL in user table?
我只写了 1 个查询,我的查询是:
I am writting only 1 query, my query is:
INSERT INTO user (name, university_id) VALUES ($name, $university_id);
这里 $university_id
可以从前端为 null.
Here $university_id
can be null from front end.
university
表将由我默认设置.
在前端,学生将选择大学名称,根据university_id
将传递给user
表,但如果学生没有选择任何大学名称,则应该将空值传递给 university_id
字段的 user
表.
In the front end, student will select the university name, according to that the university_id
will pass to user
table, but if student is not selecting any university name then is should pass null value to the user
table for university_id
field.
推荐答案
只允许表user
的university_id
列允许NULL
值,所以你可以保存空值.
Just allow column university_id
of table user
to allow NULL
value so you can save nulls.
CREATE TABLE user
(
uid INT NOT NULL,
Name VARCHAR(30) NOT NULL,
university_ID INT NULL, -- <<== this will allow field to accept NULL
CONSTRAINT user_fk FOREIGN KEY (university_ID)
REFERENCES university(university_ID)
)
更新 1
根据您的评论,您应该插入 NULL
而不是 ''
.
based on your comment, you should be inserting NULL
and not ''
.
insert into user (name,university_id) values ('harjeet', NULL)
更新 2
$university_id = !empty($university_id) ? "'$university_id'" : "NULL";
insert into user (name,university_id) values ('harjeet', $university_id);
作为旁注,该查询容易受到 SQL 注入
(s) 的变量来自外部.请查看下面的文章,了解如何预防.通过使用 PreparedStatements
,您可以摆脱在值周围使用单引号.
As a sidenote, the query is vulnerable with SQL Injection
if the value(s) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements
you can get rid of using single quotes around values.
- 如何在 PHP 中防止 SQL 注入?
这篇关于如何将空值传递给外键字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将空值传递给外键字段?


基础教程推荐
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01