This question already has answers here:
How to execute two mysql queries as one in PHP/MYSQL?
(8 answers)
Closed 6 years ago.
I am trying to create a mySQL table with php and I am getting a syntax error whenever I run my code. The string is
$sql = "DROP TABLE Colors;
CREATE TABLE Colors (
color VARCHAR(30) NOT NULL,
vote INT(16) NOT NULL UNSIGNED,
hex VARCHAR(10) NOT NULL,
PRIMARY KEY (color)
)";
query line is ($conn is the connection to the server)
$conn->query($sql)
The error is
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
'CREATE TABLE Colors (
color VARCHAR(30) NOT NULL,
vote INT(16) NOT NULL UNSIGNED' at line 2
Does anyone see what I am doing wrong?
You need to execute one statement at a time. ; is a construct used by the command-line tool as a delimiter, it's not actually used in the MySQL protocol for communicating so it's an error. The DELIMITER value can also be changed.
Split up it looks like this:
$conn->query("DROP TABLE Colors");
$conn->query("CREATE TABLE ...");
Note, I strongly encourage you to do proper error checking here and have exceptions turned on so that if a statement fails you know about it.
Not sure which mysql lib you are using, but in PHP you should use function multi_query in your scenario.
$sql = "DROP TABLE Colors;
CREATE TABLE Colors (
color VARCHAR(30) NOT NULL,
vote INT(16) NOT NULL UNSIGNED,
hex VARCHAR(10) NOT NULL,
PRIMARY KEY (color)
)";
mysqli_multi_query($conn, $sql);
Related
I have created a web you can upload and download files - everything works perfect. But now, I want to create a init file, that delete old records in database and create a new tables in it.
So I write this:
$command = "
IF OBJECT_ID(`".$database.".Users`) IS NOT NULL
DROP TABLE ".$database.".Users;
IF OBJECT_ID(`".$database.".Uploads`) IS NOT NULL
DROP TABLE ".$database.".Uploads;
CREATE TABLE `Users` (
`Id` int(11) NOT NULL,
`User` text NOT NULL,
`Password` text NOT NULL,
`Permission` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
ALTER TABLE `Users` ADD PRIMARY KEY (`Id`);
ALTER TABLE `Users` MODIFY `Id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=0;
CREATE TABLE `Uploads` (
`Id` int(11) NOT NULL,
`Name` text NOT NULL,
`User` text NOT NULL,
`Comment` text NOT NULL,
`Path` text NOT NULL,
`Permission` int(11) NOT NULL,
`Date` text NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
ALTER TABLE `Uploads` ADD PRIMARY KEY (`Id`);
ALTER TABLE `Uploads` MODIFY `Id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=0;
";
$result = mysqli_query($conn, $command) or die(mysqli_error($conn));
I think, that code is right (but obviously not). When I run it, SQL throws an 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 'IF OBJECT_ID(db.Users) IS NOT NULL DROP TABLE db.User' at line 1**.
This means that it don’t have a problem with connection to SQL database.
I tried instead of IF OBJECT_ID use IF NOT EXISTS, but it doesn't works too. Can anybody tell me if multi-line SQL command is this problem or if it is something else?
Note: I use 5.5.37 version of MariaDB (if it helps)
IF is not a valid SQL statement in MySQL / MariaDB.
The IF OBJECT_ID(...) statement in the question appears to be a Transact-SQL (Microsoft SQL Server) construct.
The equivalent functionality in MySQL would be achieved with
DROP TABLE IF EXISTS foo.mytable ;
(I expect this would work in MariaDB 5.5, but I haven't verified.)
Note that if the table doesn't exist, the execution of the statement will raise a warning. (A warning message, not an error message.)
The mysqli_query function runs a single statement. To run multiple statements, we can use mysqli_multi_query function, documented here:
http://php.net/manual/en/mysqli.multi-query.php
As far as concerns, OBJECT_ID does not exist in mysql, only in mssql. Searching for OBJECT_ID mysql 8.0 reference manual does not retun anything meaningful. Even if it existed, your syntax for IF block does not look good : you want IF...THEN...END.
To fix the error, you can replace this :
IF OBJECT_ID(`".$database.".Users`) IS NOT NULL
DROP TABLE ".$database.".Users;
IF OBJECT_ID(`".$database.".Uploads`) IS NOT NULL
DROP TABLE ".$database.".Uploads;
With :
DROP TABLE IF EXISTS ".$database.".Users;
DROP TABLE IF EXISTS ".$database.".Uploads;
never used OBJECT_ID but what you want seem to be easily doable with
"drop table if exists users;"
I keep getting this error every time i try to create a table in my sql database:
Error in query (1064): Syntax error near 'CREATE TABLE IF NOT EXISTS users ( id int(10) NOT NULL AUTO_INCREMENT, `' at line 2
Could I get some help with this?
use luke_f_db
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`trn_date` datetime NOT NULL,
PRIMARY KEY (`id`)
);
There's an error with your use command. Add an ; behind the first line or just check if the database exists and your account has access to it.
The CREATE Code worked fine for me.
You could run only one command per query**. The mySQL command line client allows you to split multiple commands with ; but still runs them sequentially.
Remove the use luke_f_db line. The database to be used should be selected within the connect command. See http://www.w3schools.com/php/func_mysqli_connect.asp:
$con = mysqli_connect("localhost","my_user","my_password","my_db");
The database name is the last argument to mysqli_connect.
The same information is found in the official PHP documentation: http://php.net/manual/en/mysqli.construct.php
** Some mySQL client implementations also allow multiple commands in one call, but you should avoid it. Using this feature in a script isn't portable to other databases and you won't ever know which of your commands triggered an error if one occurs.
This question already has answers here:
1064 error in CREATE TABLE ... TYPE=MYISAM
(5 answers)
Closed 9 years ago.
I am trying to install a php script for the statistic on my server.
This script use MySql as database. The problem is that, when I try to install it, seems that can't create the tables in the database and give me the following error message:
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 'TYPE=MyISAM' at line 5
Query : CREATE TABLE phpmv_a_category ( id int(10) unsigned NOT NULL
auto_increment, name varchar(100) default NULL, PRIMARY KEY (id) )
TYPE=MyISAM
The tables are created in a php file in this way:
$create['a_category'] =
"CREATE TABLE ".DB_TABLES_PREFIX.'a_category'." (
id int(10) unsigned NOT NULL auto_increment,
name varchar(100) default NULL,
PRIMARY KEY (id)
) TYPE=MyISAM
";
Where is the problem?
Tnx
Andra
According to the manual, TYPE is deprecated and was replaced by ENGINE in MySQL 5.5: documentation for CREATE TABLE.
It's not TYPE but instead ENGINE
ENGINE=MyISAM
SQLFiddle Demo
You are missing a ";" after ENGINE=MyISAM.
Really simple question. I forgot how to deal with this specific script. With a PHP file I create tables in mysql database. I have $query variable with the following commands:
$query = "CREATE TABLE IF NOT EXISTS `table1` (
`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`status` int(11) NOT NULL
)ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `table2` (
`something` varchar(100) NOT NULL,
`whatever` text NOT NULL
)ENGINE=MyISAM DEFAULT CHARSET=utf8;
";
It works only if I exec one single command. When I run multiple CREATE / INSERT / DROP ... commands it doesn't work. For sure there's a mistake with the syntax maybe ; and ,.
mysql_query() doesn't support multiple statements in the same call.
http://php.net/manual/en/function.mysql-query.php
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier.
You're problem doesn't comes from the SQL (well, I didn't checked it properly to be honest), but from mysql_query (assuming you're using it) : it does't allow multiple request.
http://php.net/manual/fr/function.mysql-query.php
As others have stated, the mysql_query() function doesn't support multiple queries in a single call.
On a somewhat related note, if you are able you should look into using mysql_i or PDO in place of the old mysql_*() functions, which are inferior for too many reasons to list here.
http://php.net/manual/en/book.mysqli.php
http://php.net/manual/en/book.pdo.php
I'm developing a PHP web app using a MySQL database.
I'm wondering what is the best way to find out what primary key (or any other autoincrement field) did a row receive after insertion.
Something that returns the full row as a result is also pretty good, since I also wanted to know about default values assigned to fields I didn't explicitly set.
All help is appreciated.
-- edit
So, I'm using an in-house framework that abstracts away the actual database functions, so I can't use the connection-specific "mysql_last_insert_id", and the "select last_insert_id" query, AFAIK, would be affected by other database connections, especially considering that the framework I'm using opens new connections for every query.
Guess this is a framework problem and you can't help me. If INSERT INTO had a "return inserted rows" mode, though, that would be nice.
MySQL provides a convenient way to answer this exact question:
mysql> SELECT LAST_INSERT_ID()
The mysql_* functions come with a wrapper for that: check mysql_insert_id
The mysql driver for PDO gives the same:
$pdo->exec('insert into ...');
$lastId = $pdo->lastInsertId();
Try this
MySQL CODE:
CREATE TABLE IF NOT EXISTS `mytable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`member` int(11) NOT NULL,
`update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`created` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
SHOW:
AUTO_INCREMENT
MySQL Insert:
INSERT INTO mytable (`id`,`name`,`update`,`created`) values (NULL,'TEST',NOW(),NOW());
OR
INSERT INTO mytable (`name`,`update`,`created`) values ('TEST',NOW(),NOW());
OR
INSERT INTO mytable (`name`,`created`) values ('TEST',NOW());
PHP MySQL Code:
<?php
$foo = 'test';
mysql_query("INSERT INTO mytable (`name`,`created`) values ('".mysql_real_escape_string( $foo )."',NOW())");
// GET LAST ID
$id = mysql_insert_id();
?>
In PHP use MYSQL_REAL_ESCAPE_STRING
mysql_real_escape_string( string )
See this doc mysql_real_escape_string
Bye!!
If you're using mysql_* functions, then you can simply use mysql_insert_id(). If you want the values of default rows, you'll have to select them using the key.