I can't drop a table or create a Mysql table - php

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)
)";

Related

Unable to fix a syntax error in mysql while trying to create a table

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>";
}

Check if table exist or not in PHP

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
)

FOREIGN KEY ..again

I have read and searched all the site, but nothing I had found worked for me...so please help a newbie understand what he is doing wrong.
So I am trying to create an add to favorite function.
I need to create 3 tables. The first two worked like magic, but the 3rd one ...well I got in the trouble with the FOREIGN KEY
I get no error message, but it won't create the 3rd table.
Here are my codes:
<?php
$connect = mysql_connect("127.0.0.1","root","");
$db = mysql_select_db("mydb");
mysql_query("CREATE TABLE IF NOT EXISTS users
(
userid bigint,
firstname varchar(25),
lastname varchar(15),
email varchar(250),
gender varchar(10),
username varchar(15),
password varchar(15),
age int,
activ boolean,
date TIMESTAMP NULL default CURRENT_TIMESTAMP
)ENGINE=INNODB
");
mysql_query("CREATE TABLE IF NOT EXISTS products (
productid int(11) NOT NULL AUTO_INCREMENT,
productname varchar(100) NOT NULL,
productdescription varchar(250) NOT NULL,
price decimal(6,2) NOT NULL,
PRIMARY KEY (`productid`)
) ENGINE=INNODB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ");
mysql_query("CREATE TABLE IF NOT EXISTS favorites
(
userid bigint NOT NULL,
productid int(11) NOT NULL,
PRIMARY KEY (userid, productid),
FOREIGN KEY (userid) REFERENCES user (userid) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (productid) REFERENCES product (productid) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=INNODB
");
echo "The DataBase was successfully created!";
mysql_close();
?>
The foreign keys refer to non-existing tables.
The tables are names users and products while the third table refers to them as user and product (singular).
"userid" of "user" table must be primary key.

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;;

Auto_increment stops script from creating table

My server is on hostgator running on a linux centOS.
I'm simply trying to create a table within my database and I figured out how to get the table to get created. Although when I add the AUTO_INCREMENT setting the code doesn't execute and the table isn't created.
Why would this be and how can I correct it?
Here is my code:
$members2_table = "CREATE TABLE ninja08_codin.members2(
id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(40),
last_name VARCHAR(40) NOT NULL,
email VARCHAR(64) NOT NULL,
date_joined TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
cred VARCHAR(10) NOT NULL)";
To use AUTO_INCREMENT you may have to assign the column as a primary key:
$members2_table = "CREATE TABLE ninja08_codin.members2(
id INT NOT NULL AUTO_INCREMENT,
first_name VARCHAR(40),
last_name VARCHAR(40) NOT NULL,
email VARCHAR(64) NOT NULL,
date_joined TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
cred VARCHAR(10) NOT NULL,
PRIMARY KEY (id))";
Your query will give error
there can be only one auto column and it must be defines as a key, so add primary key to id field
$members2_table = "CREATE TABLE ninja08_codin.members2(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(40),
last_name VARCHAR(40) NOT NULL,
email VARCHAR(64) NOT NULL,
date_joined TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
cred VARCHAR(10) NOT NULL)";

Categories