I want to check if the table in database exists, if not create a table with code
CREATE TABLE Topics (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
email VARCHAR(70) NOT NULL,
message TEXT
)
and if not create a table. I know I have to use it but I don't know what to use before...
If you're using MySQL, use this query:
CREATE TABLE IF NOT EXISTS Topics (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
email VARCHAR(70) NOT NULL,
message TEXT
)
It will create table only if it does not exist.
You can show tables before creating new table by run this commands together
USE database_name; -- write your database name
SHOW TABLES;
OR create table if not exit
CREATE TABLE IF NOT EXISTS Topics (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
email VARCHAR(70) NOT NULL,
message TEXT
)
Related
CREATE TABLE category(
id int(10) NOT NULL AUTO_INCREMENT,
entity_type varchar(32),
entity_id INT(10),
PRIMARY KEY (id),
FOREIGN KEY (entity_id)
)
I get an error
You have an error in your SQL syntax; it seems the error is around: '
entity_id INT(10), PRIMARY KEY (id), FOREIGN KEY (entity_id) )' at
line 3
I am unable to understand on how to fix it.
Whereas when I add this
CREATE TABLE `Image` (
`Id [PK]` int (10) ,
`EntityType` varchar(32),
`EntityId [FK]` int(10)
);
the above code fixes the error
Below is the code which gives Foreign key constraints even after I tried creating image and category table first and then adding relation to it in the User Table
$sql_image = 'CREATE TABLE IF NOT EXISTS image (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
entity_type VARCHAR(32) NOT NULL,
entity_id INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (id) )';
if ($db->database->createTable($sql_image)) { echo "Image Table Created Successfully"; }
$sql_category = 'CREATE TABLE IF NOT EXISTS category (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
entity_type VARCHAR(32) NOT NULL,
entity_id INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (id) );';
if ($db->database->createTable($sql_category)) {
echo "Category Table Created Successfully"; }
$sql_user = 'Create TABLE IF NOT EXISTS user(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name varchar(255),
last_name varchar(255),
email varchar(255),
category int(10),
status boolean,
user_profile_photo int(10),
FOREIGN KEY (user_profile_photo) references image(entity_id),
FOREIGN KEY (category) references category(entity_id) );';
if ($db->database->createTable($sql_user)) {
echo "User Table Created Successfully"; }
If you want a foreign key to be added then you need to define the reference table means in which table the entity_id belongs
CREATE TABLE category(
id int(10) NOT NULL AUTO_INCREMENT,
entity_type varchar(32),
entity_id INT(10),
PRIMARY KEY (id),
FOREIGN KEY (entity_id) REFERENCES Entity(entity_id)
)
The last line it's wrong.
Try something like this:
FOREIGN KEY (product_category, product_id)
REFERENCES product(category, id)'
FOREIGN KEY (product_category, product_id)
REFERENCES second_table(category, id)
2 errors that I can see
1) 'MySQL requires indexes on foreign keys and referenced keys'. MySQL will create keys on the referencing table(users) if you do not but you have to create them on the referenced tables on entity_id(image,category)
2) 'Corresponding columns in the foreign key and the referenced key must have similar data types. The size and sign of integer types must be the same'
see https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html
This syntaxs and generates the tables (you need to decide what kind of key k1 and k2 should be):-
drop table if exists us;
drop table if exists i;
drop table if exists c;
CREATE TABLE IF NOT EXISTS i (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
entity_type VARCHAR(32) NOT NULL,
entity_id INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (id) );
alter table i
add key k1(entity_id);
CREATE TABLE IF NOT EXISTS c (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
entity_type VARCHAR(32) NOT NULL,
entity_id INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (id) );
alter table c
add key k2(entity_id);
Create TABLE IF NOT EXISTS us(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name varchar(255),
last_name varchar(255),
email varchar(255),
category int(10) unsigned,
status boolean,
user_profile_photo int(10) unsigned,
FOREIGN KEY fk1(user_profile_photo) references i(entity_id),
FOREIGN KEY (category) references c(entity_id)
);
Verify that both table columns are defined with same data type.
Verify that both table and their columns have same collation charset should be same e.g. utf-8
Even if tables have same collation , columns still could have different one.
Verify that both columns have the same signing definition. If the referencing column is int(10) unsigned so should be the referencing
column.
In my case
column user_profile_photo from user table and id from image table were having different signing definition. hence it was not adding foreign key.
FOREIGN KEY (user_profile_photo) references image(id),
FOREIGN KEY (category) references category(id)
$sql_image = 'CREATE TABLE IF NOT EXISTS image (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, // int(10) UNSIGNED should be same as that in user table below.
entity_type VARCHAR(32) NOT NULL,
PRIMARY KEY (id)
)';
if ($db->database->createTable($sql_image)) {
echo "Image Table Created Successfully<br><br>";
}
$sql_category = 'CREATE TABLE IF NOT EXISTS category (
id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, // int(10) UNSIGNED should be same as that in user table below.
entity_type VARCHAR(32) NOT NULL,
PRIMARY KEY (id)
);';
if ($db->database->createTable($sql_category)) {
echo "Category Table Created Successfully<br><br>";
}
$sql_user = 'CREATE TABLE IF NOT EXISTS user(
id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name varchar(255),
last_name varchar(255),
email varchar(255),
category int(10) UNSIGNED NOT NULL, //int(10) UNSIGNED should be match id from category table.
status boolean,
user_profile_photo int(10) UNSIGNED NOT NULL,
FOREIGN KEY (user_profile_photo) references image(id),
FOREIGN KEY (category) references category(id)
);';
if ($db->database->createTable($sql_user)) {
echo "User Table Created Successfully<br><br>";
}
I am creating a MySQL database and this doesn't seem to work, i was able to create a review table but now i'm trying to drop that table and create a reviews table but it doesn't seem to work. Please can someone take a look at this and help me check to see what's wrong here?
$reviewsTable = "CREATE TABLE reviews (
ID int NOT NULL AUTO_INCREMENT,
Name varchar(100) NOT NULL,
Website varchar(100) NOT NULL,
Review varchar(100) NOT NULL,
TimeOfYear varchar(50),
DayOfYear varchar(50),
PRIMARY KEY (website)
)";
$drop = "DROP TABLE review";
mysqli_query($connect,$drop);
mysqli_query($connect,$reviewsTable);
Just use if exists to drop the table if there is one then create your table.
Id has to be primary key because of the auto increment. all auto increments have to be primary key. You can index website though. but i set id as primary key below this should help.
$reviewsTable = "
DROP TABLE IF EXISTS review;
CREATE TABLE reviews (
ID int NOT NULL AUTO_INCREMENT,
Name varchar(100) NOT NULL,
Website varchar(100) NOT NULL,
Review varchar(100) NOT NULL,
TimeOfYear varchar(50),
DayOfYear varchar(50),
PRIMARY KEY (ID)
)";
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;;
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.
The exact error I keep seeing is:
Key column 'alarmID' doesn't exist in table
alarmID is my primary key field.
Here is the code I have:
$sql = "CREATE TABLE IF NOT EXISTS alarms (
alaramID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (alarmID),
Title CHAR(30),
Description TEXT,
DT DATETIME
)";
Note: I am coding in PHP.
$sql = "CREATE TABLE IF NOT EXISTS alarms (
alaramID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (alaramID),
Title CHAR(30),
Description TEXT,
DT DATETIME
)";
alaramID
The primary key in your table is alaramID and note the error its alarmID.So correct the spelling in the query like this
$sql = "CREATE TABLE IF NOT EXISTS alarms (
alaramID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (alaramID),
Title CHAR(30),
Description TEXT,
DT DATETIME
)";