Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass a null value to a foreign key field?

I have 2 tables:

university:

university_id(p.k) | university_name

and user:

uid | name | university_id(f.k)

How to keep university_id NULL in user table?

I am writting only 1 query, my query is:

INSERT INTO user (name, university_id) VALUES ($name, $university_id);

Here $university_id can be null from front end.

university table will be set bydefault by me.

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.

like image 792
Harjeet Jadeja Avatar asked Feb 26 '13 06:02

Harjeet Jadeja


People also ask

How do I insert a null value in a foreign key column?

when you create the table set allow null to NOT and then apply the foreign key constraint. You can not set null on update, it should send you an error, but you can (you must) simply not update this column and update only the fields you need to change.

Can we assign null value to foreign keys?

A foreign key containing null values cannot match the values of a parent key, since a parent key by definition can have no null values. However, a null foreign key value is always valid, regardless of the value of any of its non-null parts.

How do you make a foreign key null?

A foreign key with "set null on delete" means that if a record in the parent table is deleted, then the corresponding records in the child table will have the foreign key fields set to NULL. The records in the child table will not be deleted in SQL Server.


2 Answers

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) ) 

UPDATE 1

based on your comment, you should be inserting NULL and not ''.

insert into user (name,university_id) values ('harjeet', NULL) 

UPDATE 2

$university_id = !empty($university_id) ? "'$university_id'" : "NULL"; insert into user (name,university_id) values ('harjeet', $university_id); 

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.

  • How to prevent SQL injection in PHP?
like image 61
John Woo Avatar answered Sep 19 '22 17:09

John Woo


Here suppose i have foreign key user_id and i want to insert null value for that.

enter image description here

Checkbox must be checked for insert null value for foreign key.

like image 26
Devang Rathod Avatar answered Sep 23 '22 17:09

Devang Rathod