Error creating table: Key column doesn't exist [duplicate] - php

This question already has answers here:
Can't create table (errno: 150) on FOREIGN KEY
(2 answers)
Closed 8 years ago.
I tried create these tables:
$sql = "CREATE TABLE IF NOT EXISTS Articls (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(254) COLLATE utf8_persian_ci NOT NULL
) DEFAULT COLLATE utf8_persian_ci";
$sql = "CREATE TABLE IF NOT EXISTS Tags (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
id_articls INT(10) UNSIGNED NOT NULL,
name VARCHAR(256) COLLATE utf8_persian_ci NOT NULL,
FOREIGN KEY (`Tags.id_articls`) REFERENCES Articls(`Articls.id`)
) DEFAULT COLLATE utf8_persian_ci"
;
First table create successfully but secnond I get this error:
Error creating table: Key column 'Tags.id_articls' doesn't exist in
table
If I remove Tags. in Tags.id_articls and Tags.id_articls I get errno: 150
Also If I try
$sql = "CREATE TABLE IF NOT EXISTS Tags (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
id_articls INT(10) UNSIGNED NOT NULL,
name VARCHAR(256) COLLATE utf8_persian_ci NOT NULL,
FOREIGN KEY (Tags.id_articls) REFERENCES Articls(Articls.id)
) DEFAULT COLLATE utf8_persian_ci"
I get this error:
Error creating table: You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near '.id_articls)
REFERENCES Articls(Articls.id) ) DEFAULT COLLATE utf8_persian_ci' at
line 5

The foreign key in your Tags table should be id_articls and not Tags.id_articls

Related

Can not add foreign key constraint when creating new tables [duplicate]

This question already has answers here:
MySQL Creating tables with Foreign Keys giving errno: 150
(20 answers)
Closed 1 year ago.
I'am creating a very new DB and i am getting this error when i try to add some foreign key to my tables
:
Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
Here are my codes :
$pdo->exec("CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
username VARCHAR(255) NOT NULL,
password CHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL,
ft_img VARCHAR(255) NOT NULL,
content text NOT NULL,
email VARCHAR(255) NOT NULL,
phone VARCHAR(255) NOT NULL,
role ENUM ('Author', 'Admin', 'Suscriber') NULL DEFAULT 'Suscriber',
created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
//Create posts table
$pdo->exec("CREATE TABLE posts (
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
user_id int NULL,
title VARCHAR(255) NOT NULL,
chapo VARCHAR(255) NOT NULL,
ft_img VARCHAR(255) NOT NULL,
content text NOT NULL,
created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
published TINYINT NOT NULL,
FOREIGN KEY (user_id) REFERENCES USERS (id) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
//Create comments table
$pdo->exec("CREATE TABLE comments (
id INT AUTO_INCREMENT PRIMARY KEY NOT NULL,
pseudo VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL,
content text NOT NULL,
created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
published TINYINT NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
// Create posts_comments table
$pdo->exec("CREATE TABLE posts_comments (
post_id INT UNSIGNED NOT NULL,
comment_id INT UNSIGNED NOT NULL,
PRIMARY KEY (post_id, comment_id),
CONSTRAINT fk_post
FOREIGN KEY (post_id)
REFERENCES posts (id)
ON UPDATE CASCADE
ON DELETE RESTRICT,
CONSTRAINT fk_comment
FOREIGN KEY (comment_id)
REFERENCES comments (id)
ON UPDATE CASCADE
ON DELETE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
Error message : Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
I just can not figure out why i am getting this erro, if someone can help ?
Thanks in advance,
post_id INT UNSIGNED NOT NULL,
comment_id INT UNSIGNED NOT NULL,
These are INT UNSIGNED, but they are referencing primary keys that are INT.
The data types must be the same. Signed versus unsigned is enough to make them incompatible for purposes of foreign key references.
You might like this answer that I contributed to, which is a checklist of things that can go wrong with foreign keys: https://stackoverflow.com/a/4673775/20860

Auto creating table if not existing is causing error

I'm trying to create following table . query works in phpmyadmin but doesn't work in php script. pls point out mistake in my code. Thank You
$sql = "CREATE TABLE IF NOT EXISTS `portal` (
 `id` int(255) NOT NULL AUTO_INCREMENT,
 `message_sid` varchar(255) NOT NULL,
 `name` varchar(255) NOT NULL,
 `number` varchar(255) NOT NULL,
 `message` text NOT NULL,
 `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
 `status` varchar(50) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1";
if (mysqli_query($conn, $sql)) {
echo "Table portal created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
I'm getting this error:
You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the
right syntax to use near '`id` int(255) NOT NULL AUTO_INCREMENT,
`message_sid` varchar(255) NOT NULL' at line 2
I have done this by checking if table exists in php, on false create a new table
creating table would be best to export an already existing one with phpmyadmin and then just use it as query syntax
Take the single quotes off of your table and row names
also if you make the id a primary key auto-increment, do not make it not null, this will cause a error.
I am unsure why the down votes....
CREATE TABLE IF NOT EXISTS portal (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
message_id VARCHAR(30) NOT NULL,
name VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL,
number VARCHAR(50) NOT NULL,
message text NOT NULL,
created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
status VARCHAR(50) NOT NULL )ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1
This will work

i always getting error on migration , what can i do for this kind of error

[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table def
inition; there can be only one auto column and it must be defined as a key
(SQL: create table `students` (`id` int unsigned not null auto_increment pr
imary key, `student_id` int unsigned not null auto_increment primary key, `
stuent_name` varchar(50) not null, `student_email` varchar(50) not null, `s
tudent_username` varchar(50) not null, `student_phone` varchar(50) not null
, `student_photo` text not null, `student_sex` varchar(191) not null, `stud
ent_status` varchar(191) not null, `created_at` timestamp null, `updated_at
` timestamp null) default character set utf8mb4 collate utf8mb4_unicode_ci)
i dont know what happen , this problem is happen when i try to migrate
You have two auto_increment key id and studuent_id. You can only set one as the auto increment key.

MySQL Foreign Key Constraint fails on Linux Server but works on Windows XAMPP

I have an issue that I can't figure out for the life of me. I have been creating an application in PHP/MySQL on windows using XAMPP but now I am trying to test it on a Linux based LAMP server and I get the following error when trying to create a table with foreign key constraints:
"3 - photoProjectItem table creation: Cannot add foreign key constraint"
When I run the code on XAMPP in Windows it works fine, but not within Linux. These are the tables I am trying to create:
CREATE TABLE IF NOT EXISTS generalSecurity(
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(100) NOT NULL,
firstname VARCHAR(100) NOT NULL,
secondname VARCHAR(100) NOT NULL,
accessLevel ENUM('admin', 'contributer', 'subscriber') NOT NULL,
Email VARCHAR (200) UNIQUE NOT NULL
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS generalSiteInfo (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
siteName VARCHAR(100) NOT NULL,
siteOwnerID INT(10) UNSIGNED NOT NULL,
INDEX par_id4(siteOwnerID),
FOREIGN KEY(siteOwnerID)
REFERENCES generalSecurity(id)
ON DELETE CASCADE,
siteEmail VARCHAR(100) NOT NULL,
siteAbout VARCHAR(9999) NOT NULL,
currentTheme VARCHAR(1000) NOT NULL,
siteCreateDate TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS Project (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
projectAuthorID INT(10) UNSIGNED NOT NULL,
INDEX par_id(projectAuthorID),
FOREIGN KEY(projectAuthorID)
REFERENCES generalSecurity(id)
ON DELETE CASCADE,
projectName VARCHAR(100) NOT NULL,
projectBlurb VARCHAR(5000) NULL,
projectTheme VARCHAR(100) NOT NULL,
projectDate TIMESTAMP
) ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS ProjectItem (
id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
authorID INT(10) UNSIGNED NOT NULL,
INDEX par_id2(authorID),
FOREIGN KEY(authorID)
REFERENCES generalSecurity(id)
ON DELETE CASCADE,
projectID INT(10) UNSIGNED NOT NULL,
INDEX par_id3(projectID),
FOREIGN KEY(projectID)
REFERENCES project(id)
ON DELETE CASCADE,
itemType ENUM('image', 'text') NOT NULL,
photoFileName VARCHAR(100) NULL,
itemName VARCHAR(1000) NOT NULL,
entry VARCHAR(5000) NULL,
photoMeta VARCHAR(5000) NOT NULL,
date TIMESTAMP,
deleted BOOLEAN NOT NULL
) ENGINE=INNODB;
it fails when trying to create table "ProjectItem". Can you guys see anything I am missing?
I really appreciate any help that can be given
---edit---
it works when I remove the lines
INDEX par_id3(projectID),
FOREIGN KEY(projectID)
REFERENCES project(id)
ON DELETE CASCADE,
but I can't see any obvious issues with the relationship
The issue was that apparantly MYSQL in Linux is case sensitive whereas in Windows it doesn't appear to be. I was trying to create a relationship for the table "project" when it is called "Project"

PDOException error in mysql SQL syntax [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I am trying to create 2 tables in the same MySQL database with a PHP-script:
table 'user' with primary key 'user_id' and table 'order' with primary key 'order_id' and foreign key 'user_id' from the 'user' table (1 to many relationship).
Table user creates successfully without problems:
$sql="CREATE TABLE user(
user_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
type ENUM('member','admin') NOT NULL,
username VARCHAR(30) NOT NULL,
email VARCHAR(80) NOT NULL,
pass VARBINARY(32) NOT NULL,
first_name VARCHAR(40) NOT NULL,
last_name VARCHAR(40) NOT NULL,
date_expires DATE NOT NULL,
date_created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
date_modified TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (user_id),
UNIQUE (username),
UNIQUE (email)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
However, I am not able to create table order:
$sql="CREATE TABLE order(
order_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
transaction_id VARCHAR(19) NOT NULL,
payment_status VARCHAR(15) NOT NULL,
payment_amount DECIMAL(6,2) UNSIGNED NOT NULL,
payment_date_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (order_id),
FOREIGN KEY (user_id) REFERENCES user (user_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
I get the following error:
Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order( order_id INT UNSIGNED NOT NULL AUTO_INCREMENT, user_id ' at line 1
Already checked the syntax and cannot find the mistake. Could you please advise what went wrong? Thanks a lot.
You need to escape reserved words like order with backticks
CREATE TABLE `order` ( ...
or better use another name instead.
order is keyword used by mysql like (select from tbl_name order by id ASC) so for escaping from using keywords you have to use quotes `` to avoid my sql error
so your query should by
$sql="CREATE TABLE `order` (
order_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id INT UNSIGNED NOT NULL,
transaction_id VARCHAR(19) NOT NULL,
payment_status VARCHAR(15) NOT NULL,
payment_amount DECIMAL(6,2) UNSIGNED NOT NULL,
payment_date_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (order_id),
FOREIGN KEY (user_id) REFERENCES user (user_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8";
enjoy :D

Categories