I used to a function FOREIGN KEY for link two tables together.
I'm straggling with that error: "errno: 150 "Foreign key constraint is incorrectly formed".
I could not find out where is problem. Please, I will thankful for any suggestions.
Thank, you for help.
This is my script written in PHP(see below).
<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "myDB";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connection_error);
}
echo "Connected successfully";
$sql = "CREATE DATABASE IF NOT EXISTS myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$sql = "CREATE TABLE IF NOT EXISTS us_tAddress (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
country VARCHAR(100),
city VARCHAR(100),
zip VARCHAR(100),
street VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ";
if ($conn->query($sql) === TRUE) {
echo "Table us_tAddress created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$sql = "CREATE TABLE IF NOT EXISTS us_tUser (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
address_id INT (6),
first_name VARCHAR(100),
last_name VARCHAR(100),
position VARCHAR(100),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (address_id) REFERENCES us_tAddress (id)
) ";
if ($conn->query($sql) === TRUE) {
echo "Table us_tUser created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close ();
?>
Your fields have different datatype.
Referenced column is id from us_tAddress with type id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY.
Referencing column is address_id from us_tUser with type INT (6).
You have to change type of id column in table us_tAddress to SIGNED or change datatype of field address_id in table us_tUser to UNSIGNED.
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.