foreign key

Asked

Viewed 53 times

1

I’m having trouble recording null value in foreign key. When I save to my phonebook with id_pessoa blank, it records 0 and not null. How can I fix it?

This I 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();
?>

1 answer

0


This is because if you pass a value as an empty string in a field that is INT, Mysql puts 0.

For this, you just have to work the variable $id_pessoa to carry the value of NULL for Mysql when empty. Ex:

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

In 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);
  • thanks friend worked perfectly..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.