简体   繁体   中英

How to allow NULL value on foreign key on php

Good day. I am seeking for help on what to do with the codes: The PHP part:

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){

  $student = $_POST['student']; 
  $lecture = $_POST['lecture'];
  $room = $_POST['room'];

  $students = mysqli_query($con,"SELECT * FROM students WHERE student='$student'");
  $lectures = mysqli_query($con,"SELECT * FROM lectures WHERE lecture='$lecture'");
  $rooms = mysqli_query($con,"SELECT * FROM rooms WHERE room='$room'");

  $student_row = mysqli_fetch_array($students);
  $lecture_row = mysqli_fetch_array($lectures);
  $room_row = mysqli_fetch_array($rooms);

What I want to do in this part is, if there is no entry on room input insert the value null in the room_id column in the reference table:

  if($student != $student_row['student']) {
    $addStudent = mysqli_query($con,"INSERT IGNORE INTO students (student) VALUES ('$student')");
    $studentID = mysqli_insert_id($con);
  }else{
    $studentID = $student_row['student_id'];
  };

  if($lecture != $lecture_row['lecture']) {
    $addLecture = mysqli_query($con,"INSERT IGNORE INTO lectures (lecture) VALUES ('$lecture')");
    $lectureID = mysqli_insert_id($con);
  }else{
    $lectureID = $lecture_row['lecture_id'];
  };

  if($room != $room_row['room']) {
    $addRoom = mysqli_query($con,"INSERT IGNORE INTO rooms (room) VALUES ('$room')");
    $roomID = mysqli_insert_id($con);
  }else{
    $roomID = $room_row['room_id'];
  };

I think this is the part that needs to be changed:

  $addClass = mysqli_query($con,"INSERT INTO classes (student_id,lecture_id,room_id) VALUES ('$studentID','$lectureID','$roomID')");

  if($addClass){
    echo 'Success';
  }else{
    echo 'Error: '.mysqli_error($con);
  };
};
?>

The HTML part:

<html>
<title>Add Class</title>
<body>
  <form name="Add Class" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    Student: <input type="text" name="student" />
    </br></br>
    Lecture: <input type="text" name="lecture" />
    </br></br>
    Room: <input type="text" name="room" />
    </br></br>
    <input type="submit" value="Add Class">
  </form>
</body>
</html>

Thank you.

You can simply insert NULL as value. Like this:

if(empty($room))
  $room = "NULL";

right before the mysqli insert. Make sure you actually pass the string null not empty or 0.

Oh and you obviously need to make sure the column is not marked as NOT NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM