I am trying to create two tables in an existing database using PHP and Mysql, but every time I try I get an error message "Error creating table: Cannot add foreign key constraint". My question was marked as duplicated, but here primary key and foreign key are exactly of the same type (INT), so I am still unable to undestand where is my error.
<?php
....
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE Users (
id INT AUTO_INCREMENT PRIMARY KEY,
nome VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL
)";
// sql to create table
$sql = "CREATE TABLE Messaggi (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
messaggio TEXT NOT NULL,
utente INT,
FOREIGN KEY (utente) REFERENCES Users(id),
reg_date TIMESTAMP
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
I think there is an error in my declaration of FOREIGN KEY but I can't find it. Can anybody help me? Thanks a lot!