I need to do batch MYSQL insert/updates. I got batch insert statement to work, but when the insert comes as multiple one liners it does not.. Similarly I have not been able to generate a batch update. Please see examples below.
Batch insert statement works
$sql = "INSERT INTO `test` (`somefield`) VALUES ('test', 'test');";
db::statement($sql);
Multiple separate insert statements NOT working
$sql = "INSERT INTO `test` (`somefield`) VALUES ('test'); INSERT INTO `test` (`somefield`) VALUES ('test');";
db::statement($sql);
SQLSTATE[42000]: Syntax error or access violation: 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 'INSERT INTO test (somefield) VALUES ('test')' at line 1 (SQL: INSERT INTO test (somefield) VALUES ('test'); INSERT INTO test (somefield) VALUES ('test');)
Batch update statement not working
$sql = "INSERT INTO 'flights' (`id`, `airline`) VALUES ('142832', 'BA') ON DUPLICATE KEY UPDATE `airline`=VALUES(`airline`);"
db::statement($sql);
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 ''flights' (id, airline) VALUES ('142832', 'BA') ON DUPLICATE KEY UP' at line 1
Reviewed multiple Stackoverflow posts - but I am getting something wrong
Multiple insert statements - Multiple SQL Update Statements in single query
Batch update statement - Multiple Updates in MySQL
Would appreciate help on this - thanks!
This is weird. at a quick glance it appears that the batch statement is wrong, which is supposedly working.
A semantically correct batch statement would have the brackets separate each row of data, ie. like this:
INSERT INTO test
VALUES
('test1')
, ('test2')
, ('test3');
The separate insert statements look fine, however, your database driver might not support multiple statements in its statement method (most don't, AFAIK). The work around would be to start a transaction from your client, loop through the array of statements and execute. Then when all the statements execute, commit if there were no errors, or roll back the transaction. The first option is faster though.
The update statement doesn't work because the tablename flights is quoted using single-quotes. If you want to quote schema / table / column identifiers, use back-ticks, and reserve single-quotes for string values & dates, as you have done elsewhere in the same query. It is only necessary to escape a database element name if it is a reserved word, but naming database elements things like 'into', 'user', etc. is bad practice and should be avoided.
INSERT INTO flights (`id`, `airline`)
VALUES
('142832', 'BA')
ON DUPLICATE KEY UPDATE
airline=VALUES(`airline`)
Try to unquote flights, or quote it with back ticks in your last query (the batch update statement).
Related
I am trying to get insertedid after I insert multiple row in mysql table by using this query
insert into sometable (id , candidateid , createdby)
values ('61','3175','1425'),('60','3175','1425'),('42','3175','1425'),('61','3176','1425'),('60','3176','1425'),('42','3176','1425') OUTPUT INSERTED.id
but I am getting sql syntax error
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage: "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 'OUTPUT INSERTED.id' at line 2",
sqlState: '42000',
how can I get insertion id
The OUTPUT INSERTED syntax is a Microsoft SQL Server thing. That syntax is not supported by MySQL.
In your example, you have set the id values explicitly, so there's no need for them to be returned. Just get them from your own values which you apparently already knew before you did the INSERT.
You might be relying on auto-incremented id's, which are generated during the INSERT.
To get the auto-increment id of the most recently inserted row, use the LAST_INSERT_ID() function in a separate query after your INSERT.
LAST_INSERT_ID() returns only the first id generated during your insert. If you do a multi-row insert, then it's up to you to extrapolate the subsequent id's. They are usually consecutive values. For example, the MySQL JDBC driver relies on them being consecutive values so it can return the set of id's after a batch insert.
But they are not guaranteed to be consecutive values if you have changed innodb_autoinc_lock_mode=2 which allocates the auto-inc values in an "interleaved" manner, so concurrent inserts may grab a value from the sequence in between the set your multi-row insert is generating. This is not the default mode, so you would have set it deliberately.
I've never used IF's before in SQL. I need to update a row where institution is a specific number if it exists and insert it if it doesn't. In order to avoid using first a select and then a insert or update I wanted to try my hand at an IF statement. I figured from what I've read in the documentation that it should go something like this:
IF (NOT EXISTS(SELECT evaluations FROM tEvaluations WHERE institution = 0))
BEGIN
INSERT INTO tEvaluations (institution,evaluations) VALUES (0,0)
END
ELSE
BEGIN
UPDATE tEvaluations SET evaluations = 10 WHERE institution = 0
END
However I get this error:
#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 'BEGIN
INSERT INTO tEvaluations (institution,evaluations) VALUES (0,0)
END' at line 2
I'm trying to run this query in phpmyadmin to test out how the query should be.
You can't have if..else block in normal SQL statement unless it's inside a procedural block. To me looks like you are looking for INSERT ON DUPLICATE KEY UPDATE like
INSERT INTO tEvaluations (institution,evaluations) VALUES (0,0)
ON DUPLICATE KEY UPDATE evaluations = 10;
Per documentation, either of your column should have a UNIQUE constraint defined against it. Quoting from documentation
If you specify an ON DUPLICATE KEY UPDATE clause and a row to be
inserted would cause a duplicate value in a UNIQUE index or PRIMARY
KEY, an UPDATE of the old row occurs. For example, if column a is
declared as UNIQUE and contains the value 1
I am very new to Sql, so bear with me. I have run a query the following query:
INSERT INTO adhoc_dt.`table` (id, name) VALUES(53098974, 'John');
however, by accident I run it twice. I would like to remove the duplicate. How can that be done?
I tried
INSERT INTO adhoc_dt.`table` (id, name) VALUES(53098974, 'John');
but get an error:
SQL ERROR [1064][42000]: 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
If your table name include special char of reserved word then you should enclose the table name with backticks:
`table`
But looking to your question, the table name seems:
`adhoc_dt.`table`
In this case, the correct syntax for delete is:
DELETE FROM adhoc_dt.`table`
WHERE id = 53098974 AND name = 'JOHN'
but in this way you delete all the rows with:
id = 53098974 AND name = 'JOHN'
You have to follow steps
truncate table
apply unique constraint on ID
run insert script
Hello stackoverflow's friends i need your help with this sql clausule this is the error into mysql:
_mysql_exceptions.ProgrammingError: (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 'WHERE email='Tysaic0344#gmail.com'' at line 1")
and this is my code:
INSERT INTO user (token) VALUES (1) WHERE email='example#email.com'
You cannot insert values into an existing row. You can either update or delete the existing records. In your case, I think you want to update the existing row. You can use UPDATE.
UPDATE user SET token = 1 WHERE email = 'example#email.com';
If you want to add records to the table use INSERT
INSERT INTO user VALUES (1, 'example#email.com');
Here is the link for your reference
https://msdn.microsoft.com/en-us/library/bb243852(v=office.12).aspx
You can't INSERT with a WHERE clause.
If you need to UPDATE the record where you have the email from:
UPDATE user
Set token = 1
WHERE email='example#email.com'
Or INSERT with email
INSERT INTO user (token, email)
VALUES (1, 'example#email.com')
(or without)
INSERT INTO user (token)
VALUES (1)
These kind of errors you MUST be able to fix by yourself, the error even tells you where it went wrong (at the end it says "near 'WHERE...").
Check the docs that dns_nx included (especially https://dev.mysql.com/doc/refman/5.7/en/update.html ) for the correct syntax to do an update.
You cannot INSERT a value into an existing row. The WHERE clause is invalid with INSERT. If you want to update an existing row, then you have to UPDATE the field like this:
UPDATE
user
SET
token = 1
WHERE
email='example#email.com'
Please review the docs about INSERT and UPDATE
https://dev.mysql.com/doc/refman/5.7/en/update.html
https://dev.mysql.com/doc/refman/5.7/en/insert.html
INSERT inserts new rows into a table. The WHERE clause is used to filter existing rows from a table. It doesn't make sense in a INSERT query; that's why the INSERT statement does not contain a WHERE clause.
The WHERE clause is used to filter the rows to fetch from the table (the SELECT statement), the rows to modify (the UPDATE statement) or to remove from the table (the DELETE statement).
Your query looks like you want to modify the data already existing in the table. The UPDATE statement you need looks like this:
UPDATE user SET token = 1 WHERE email = 'example#email.com'
I am trying to use IF EXISTS in MySQL but i keep getting syntax errors and I have researched for correct syntax but everything isnt working...
What i need is:
If query exists then UPDATE else INSERT new...
$queryString = "IF EXISTS (SELECT * FROM $ONCALL_TABLE WHERE uid='$contextUser' AND submitid='$submitid' AND submitstatus=3) THEN UPDATE $ONCALL_TABLE SET uid='$contextUser', start_time='$onStr', end_time='$offStr', amount='$amount' ELSE INSERT INTO $ONCALL_TABLE (uid, start_time, end_time, amount) VALUES ('$contextUser','$onStr', '$offStr', '$amount') END IF";
Error message:
Can't perform query: 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 'IF EXISTS (SELECT * FROM timesheet_oncall WHERE uid='admin' AND submitid='136545' at line 1
REPLACE INTO is what you need. http://dev.mysql.com/doc/refman/5.0/en/replace.html
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
In your case
REPLACE INTO
$ONCALL_TABLE (uid, start_time, end_time, amount)
VALUES ('$contextUser','$onStr', '$offStr', '$amount')
WHERE uid='$contextUser';
Assuming uid is a PRIMARY KEY or UNIQUE KEY
NOTE: Since the code in your question contains SQL injection flaws I would recommend you to read this article. http://php.net/manual/en/security.database.sql-injection.php