PDOException error in mysql SQL syntax [duplicate] - php

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

Related

1.6.1.24 update to 1.7.7.4 database schema error [duplicate]

ERROR 1265: Data truncated for column 'profile_pic' at row 1
SQL Statement:
ALTER TABLE `student`.`student_info`
CHANGE COLUMN `profile_pic` `profile_pic` VARCHAR(50) NOT NULL DEFAULT 'images/profile.png'
ERROR: Error when running failback script. Details follow.
ERROR 1050: Table 'student_info' already exists
SQL Statement:
CREATE TABLE `student_info` (
`name` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`profile_pic` varchar(500) DEFAULT 'images/profile.png',
PRIMARY KEY (`email`),
UNIQUE KEY `email_UNIQUE` (`email`),
UNIQUE KEY `password_UNIQUE` (`password`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
this error is flashing when i am setting the value of profile_pic column as not null however if i am not not doing so this error is not occurring can any body please explain me why is this error occurring and how to remove this
Change your Alter query to
ALTER TABLE `student`.`student_info`
CHANGE COLUMN `profile_pic` `profile_pic` VARCHAR(500) NOT NULL DEFAULT 'images/profile.png'
In your schema you have previously defined profile_pic with varchar(500) now you are trying to set it not null but with varchar(50) so your column contains the data which is longer than 50 characters therefore you see this truncated error

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

ERROR 1005 (HY000): Can't create table 'db.POSTS' (errno: 150)

Hi I'm having issues creating my post database. I'm trying to make a forenge key to link to my users database. Can someone please help?
Here's the code for my tables :
CREATE TABLE USERS(
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (userID,UserName)
)ENGINE=InnoDB;
CREATE TABLE POSTS(
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
postAuthor varchar(255),
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(postAuthor) REFERENCES USERS(UserName)
)ENGINE=InnoDB;
Here's the last InnoDB error message:
Error in foreign key constraint of table db/POSTS:
FOREIGN KEY(postAuthor) REFERENCES USERS(UserName)
)ENGINE=InnoDB:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
There really should not be a good reason to have a compound primary key on the first table. So, I think you intend:
CREATE TABLE USERS (
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (userID),
UNIQUE (UserName)
);
CREATE TABLE POSTS (
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
postAuthor int,
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(postAuthor) REFERENCES USERS(UserId)
);
Some notes:
An auto-incremented id is unique on every row. It makes a good primary key.
A primary key can consist of multiple columns (called a composite primary key). However, an auto-incremented id doesn't make much sense as one of the columns. Just use such an id itself.
If you use a composite primary key, then the foreign key references need to include all columns.
I chose UserId for the foreign key reference. You could also use UserName (because it is unique).
UserName is a bad choice for foreign keys, because -- conceivably -- a user could change his or her name.
The error is caused by incorrect foreign key definition. In the concrete case you are missing a complete column in your foreign key definition.
In the USERS table you have defined primary key as composite key of UserID and UserName columns.
CREATE TABLE USERS (
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (UserID,UserName)
) ENGINE=InnoDB;
note that it is good practice to respect case of the identifiers (column names)
In the POSTS table you declared your foreign key to reference only one column in the USERS table, the UserName column. This is incorrect as you need to reference entire primary key of the USERS table which is (UserID, UserName). So to fix the error you need to add one additional column to the POSTS table and change your foreign key definition like this:
CREATE TABLE POSTS(
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
authorId int,
postAuthor varchar(255),
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(authorId, postAuthor) REFERENCES USERS(UserID, UserName)
) ENGINE=InnoDB;
Please look at following fiddle: http://sqlfiddle.com/#!9/92ff1/1
NOTE: If you can you should re-architect this to not use the composite primary key in the USERS table as it does not make sense from what I can see in the displayed code. You can change the tables like this:
CREATE TABLE USERS (
UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (UserID)
) ENGINE=InnoDB;
CREATE TABLE POSTS (
postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
postAuthorID int,
tag varchar(255),
PRIMARY KEY(postID),
FOREIGN KEY(postAuthorID) REFERENCES USERS(UserID)
) ENGINE=InnoDB;;

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

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

"Key column 'username' doesn't exist in table"

I am creating three tables and when trying to tie the primary and foreign keys I am receiving the error message "Key column 'username' doesn't exist in table".
Could someone take a look at my code and tell me what I am doing wrong? I have tried dropping the database and revamped the tables a few times but I am still getting the same message. Here is my code, thank you in advance for any help!
create database testproject
use testproject
create table caller_info
(
caller_id int(11) unsigned auto_increment primary key not null,
first_name varchar(35) not null,
Last_name varchar(35) not null,
phone_number int(25) not null
);
create table caller_call_record
(
call_record_id int(11),
Call_Description varchar(50),
franchise_id int(10) not null,
email varchar(40) not null,
username varchar(25) primary key not null
);
create table caller_escalation
(
call_escalation_id int(11) unsigned auto_increment not null,
Second_Level varchar(5) not null,
caller_id int(11) not null,
PRIMARY KEY(call_escalation_id),
FOREIGN KEY(caller_id)
REFERENCES caller_info(caller_id),
FOREIGN KEY(username) REFERENCES caller_call_record(username)
);
As pointed out, your table caller_escalation needs a column called username in order to create the foreign key.
It sounds like once you've added that, you're now getting a Cannot add foreign key constraint error from MySQL. The first thing that comes to mind with this kind of error is that you're using the wrong engine for your tables. You are most likely using MyISAM which does not support foreign key references - in order to use these, you will need to change the engine on all of your tables to InnoDB.
try this:
create table caller_call_record
(
call_record_id int(11),
Call_Description varchar(50),
franchise_id int(10) not null,
email varchar(40) not null,
username varchar(25) not null,
PRIMARY KEY (username)
);
create table caller_escalation
(
call_escalation_id int(11) unsigned auto_increment not null,
Second_Level varchar(5) not null,
caller_id int(11) not null,
username varchar(25) not null,
PRIMARY KEY(call_escalation_id,username),
FOREIGN KEY(caller_id)
REFERENCES caller_info(caller_id),
FOREIGN KEY(username) REFERENCES caller_call_record
);
The table caller_escalation also needs a column username, which is not there
create table caller_escalation
(
call_escalation_id int(11) unsigned auto_increment not null,
Second_Level varchar(5) not null,
caller_id int(11) unsigned not null, ;; <--- added unsigned type here
PRIMARY KEY(call_escalation_id),
username varchar(25) not null, ;; <--- added field here
FOREIGN KEY(caller_id)
REFERENCES caller_info(caller_id),
FOREIGN KEY (username) REFERENCES caller_call_record (username)
);
Also ensure the column data types are the same in both tables. You have "caller_id int(11) unsigned" in caller_info and "caller_id int(11)" in caller_escalation. I added the unsigned specifier above to make it work.

Categories