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;"
Related
I want to run a .sql file from my server in Codeigniter 3.1.0. I have tried following
//code to create a DB & this is successful then following ocde
$query = file_get_contents('./test.sql');
$this->db->query($query);
Here is my test.sql file. https://gist.github.com/rejoan/97dfae1b08116e386b3e6fda97eeb4f7
Now when I run this it shows error always
A Database Error Occurred
Error Number: 1064
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 user ( id int(11) NOT NULL, test_id int(11)
NOT NULL, `' at line 10
CREATE TABLE `test`
( `id` int(11) NOT NULL,
`name` varchar(250) NOT NULL,
`description` text NOT NULL,
`added` date NOT NULL,
`outdate` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `user`
( `id` int(11) NOT NULL,
`test_id` int(11) NOT NULL,
`name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `test` ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `name` (`name`);
ALTER TABLE `user` ADD PRIMARY KEY (`id`),
ADD KEY `test_id` (`test_id`);
ALTER TABLE `test` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=37;
ALTER TABLE `user` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE `user`
ADD CONSTRAINT `FK_user_test` FOREIGN KEY (`test_id`)
REFERENCES `test` (`id`) ON UPDATE NO ACTION;
Filename: C:/xampp/htdocs/spider_clients/system/database/DB_driver.php
Line Number: 691
So how can I resolve this by issue? I have a idea to do this by PHP raw code but Firstly I want to solve by CI. Any Idea?
** Even I have tried by replacing all backtick by single quote still not works
You can't run any SQL file through the API. Not even if you split up the file and run one query per API call.
There are some commands that can appear in SQL files, but they're actually mysql client builtin commands. These commands are not recognized by the SQL parser in the server.
It's tricky to split up the SQL file. There are SQL statements that contain literal semicolons, like CREATE TRIGGER. So you need more complex logic to split up the file, it's not as simple as preg_split('/;/', $query)
Another gotcha: you'll find that submitting a "query" that consists of nothing but an SQL comment causes an error.
Also, if your SQL file is too large, you'll blow out PHP's max memory if you use file_get_contents().
The bottom line is that you'll waste a lot of your time developing this code and trying to make it work. You're better off leveraging the tool that is already designed to run SQL scripts:
shell_exec("mysql databasename < ./test.sql");
See also:
Running MySQL *.sql files in PHP
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.
Hi I'm trying to create some temporary tables in mysql using php
my code:
<?php
mysql_connect("localhost","root","sahan");//database connection
mysql_select_db("callcenter");
$maketemp="create table #temp1 (id varchar(50),date varchar(50),csc varchar(50),effectedareas varchar(50),agent varchar(50))";
$data1 = mysql_query($maketemp)
or die(mysql_error());
?>
but it gives an error "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 '' at line 1"
My MySQL version is as below
MySQL Ver 14.12 Distrib 5.0.77, for redhat-linux-gnu (i686) using readline 5.1
I'm not much fluent in php coding please can some one help me??
I do not know why you want a table name like that but you need indentifier quotes (backticks) for it to work.
`#temp1`
You need quotes or else it will considered a comment. #
$maketemp = "CREATE TABLE `#temp1` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`date` varchar(50),
`csc` varchar(50),
`effectedareas` varchar(50),
`agent` varchar(50),
PRIMARY KEY (`id`)
) COLLATE = 'utf8_general_ci'
";
Please refrain from using mysql_* functions, they are deprecated. Click here.
Here problem is declaring varchar for primay key with auto increment. So make id datatype to int. then its working
$maketemp = "CREATE TABLE `#temp1` (
`id` VARCHAR(50) NOT NULL AUTO_INCREMENT,
`date` varchar(50),
`csc` varchar(50),
`effectedareas` varchar(50),
`agent` varchar(50),
PRIMARY KEY (`id`)
) COLLATE = 'utf8_general_ci'
";
If you want to create temporary table, In my sql, there is temporary table functionality as
http://www.mysqltutorial.org/mysql-temporary-table/
Taken from MySQL Temporary Tables
Temporary tables were added in MySQL version 3.23. If you use an older version of MySQL than 3.23, you can't use temporary tables, but you can use heap tables.
You are mixing up SQLServer syntax with MySQL syntax. While you are able to create a temporary table in SQLServer with #table or a gloabal temporary table with ##table in MySQL you have to use the keyword TEMPORARY
CREATE TEMPORARY TABLE temp1 (
id varchar(50)
,date varchar(50)
,csc varchar(50)
,effectedareas varchar(50)
,agent varchar(50)
)
CREATE TABLE IF NOT EXISTS `$id` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`start` varchar(10) NOT NULL,
`end` varchar(10) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=45 ;
INSERT INTO `$id`(`start`, `end`) VALUES ('0','0')
I have been trying to figure out how I can bind these two Mysql(requests(?)) into one with no success. Basically I want it to work so when I create the table it should also add the values 0 and 0 to "start" and "end" rows. But I still want the "Create table if not exists" to be in effect for the INSERT INTO. So if the table exist don't INSERT either.
You could do that with following single statement:
CREATE TABLE IF NOT EXISTS `$id` (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`start` VARCHAR(10) NOT NULL,
`end` VARCHAR(10) NOT NULL,
`date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB
SELECT '0' AS `start`, '0' AS `end`;
You use the CREATE TABLE ... SELECT syntax with selecting not from a table, but constant values and get the autoincrement value and the current_timestamp by default.
as of MySQL 5.5.6 or newer, see following excerpt from the manual, CREATE TABLE ... SELECT:
As of MySQL 5.5.6, handling of CREATE TABLE IF NOT EXISTS ... SELECT
statements was changed for the case that the destination table already
exists. This change also involves a change in MySQL 5.1 beginning with
5.1.51.
Previously, for CREATE TABLE IF NOT EXISTS ... SELECT, MySQL produced
a warning that the table exists, but inserted the rows and wrote the
statement to the binary log anyway. By contrast, CREATE TABLE ...
SELECT (without IF NOT EXISTS) failed with an error, but MySQL
inserted no rows and did not write the statement to the binary log.
MySQL now handles both statements the same way when the destination
table exists, in that neither statement inserts rows or is written to
the binary log. The difference between them is that MySQL produces a
warning when IF NOT EXISTS is present and an error when it is not.
This change means that, for the preceding example, the CREATE TABLE IF
NOT EXISTS ... SELECT statement inserts nothing into the destination
table as of MySQL 5.5.6.
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.