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

前端 未结 3 1757
庸人自扰
庸人自扰 2020-12-10 10:32

I have 2 tables:

university:

university_id(p.k) | university_name

and user:

uid | name |          


        
相关标签:
3条回答
  • 2020-12-10 10:50

    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.

    0 讨论(0)
  • 2020-12-10 11:01

    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?
    0 讨论(0)
  • 2020-12-10 11:02

    I was using MySQL InnoDB and even allowing NULL in the FK column and using NULL as default I was getting an error. So I used the SET syntax:

    INSERT INTO (table) SET value1=X...
    

    And I just don't set the FK column.

    0 讨论(0)
提交回复
热议问题