foreign key

1

I'm having trouble writing null value to a foreign key. When I write to the directory with blank%%, it writes 0 instead of null. How can I fix this?

This is my code and table:

person:

id_pessoa int(11) NOT NULL AUTO_INCREMENT,
ds_pessoa varchar(20) DEFAULT NULL,
agenda:
id_agenda  int(11) NOT NULL AUTO_INCREMENT,
hr_agendamento time(11) DEFAULT NULL,
id_pessoa int(11) DEFAULT NULL,

php code

<?php
$hr_agendamento = $_POST['hr_agendamento'];
$id_pessoa = $_POST['id_pessoa'];

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO agenda (hr_agendamento, id_pessoa)
VALUES ( $hr_agendamento, $id_pessoa)";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
    
asked by anonymous 24.08.2017 / 15:04

1 answer

0

This occurs because if you pass a value as an empty string in a field that is INT , MySQL places 0 .

For this, you only have to work with the variable $id_pessoa to take the value of NULL to MySQL when it is empty. Ex:

$id_pessoa = $_POST['id_pessoa'];
if(empty($id_pessoa)) {
  $id_pessoa = 'NULL';
}

Doing so, when you concatenate the variable in the query, it prints something like:

INSERT INTO agenda (hr_agendamento, id_pessoa) VALUES ( 'XX:XX', NULL);
    
24.08.2017 / 15:09