简体   繁体   中英

Mysql Create Table If Not Exists else… Information Schema

Quick one hopefully - not sure where I'm going wrong here but this doesn't seem to work full stop.

Running MySQL query through PHP...

Current code

$uu = mysql_query("
IF EXISTS(SELECT table_name FROM information_schema.tables 
WHERE table_schema = 'schema_example' AND table_name = 'test_q')
THEN
insert into `test_q` (code, va_desc, price, category) 
values ('$code', '$desc', '$price', '$categ') 
on duplicate key update va_desc='$desc', price='$price', category='$categ'
ELSE
CREATE TABLE `test_quote` (
`code` varchar(30) NOT NULL,
`va_desc` text NOT NULL,
`price` text NOT NULL,
`category` text NOT NULL,
PRIMARY KEY (`code`),
UNIQUE KEY `id` (`code`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
insert into `test_q` (code, va_desc, price, category) 
values ('$code', '$desc', '$price', '$categ')
END IF;
")or die(mysql_error());

Really appreciate some help on what I need to change, at the moment this does absolutely nothing and doesn't return any specific errors. :/

Having said that if I run it in phpMyAdmin it returns the following (although I can't understand why):

#1064 - 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 
'ELSE CREATE TABLE `test_quote`(
`code` varchar(30) NOT NULL,
`va_desc` text NO' at line 7 

You don't need to query INFORMATION_SCHEMA . You can use the IF NOT EXISTS option to CREATE TABLE .

mysql_query("CREATE TABLE IF NOT EXISTS `test_q` (
    `code` varchar(30) NOT NULL,
    `va_desc` text NOT NULL,
    `price` text NOT NULL,
    `category` text NOT NULL,
    PRIMARY KEY (`code`),
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1");
mysql_query("insert into `test_q` (code, va_desc, price, category) 
            values ('$code', '$desc', '$price', '$categ') 
            on duplicate key update va_desc='$desc', price='$price', category='$categ'");

Also, a primary key is a unique key, you don't need to specify them both when you create the table.

Trying using the following query as if, else and then statements are not supported in the sql query, for that you can stored procedures.

mysql_query("CREATE TABLE IF NOT EXISTS `test_q` (`code` varchar(30) NOT NULL,
`va_desc` text NOT NULL,
`price` text NOT NULL,
`category` text NOT NULL,
PRIMARY KEY (`code`),
);
mysql_query("insert into `test_q` (code, va_desc, price, category) 
        values ('$code', '$desc', '$price', '$categ') 
        on duplicate key update va_desc='$desc', price='$price', category='$categ'");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM