Why this SQL query does not work? - mysql

I wrote this query but I get the following error:
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[42000]: Syntax error or access violation: 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 forum_topics_track (userid, topic_id, `c' at line 3
I guess it is self explanatory but my goal is to check if the record exists and if it doesn't, to insert it.
IF NOT EXISTS
(SELECT * FROM `forum_topics_track` WHERE `userid` = '{$userid}' AND `topic_id` = '{$topic_id}')
BEGIN
INSERT INTO `forum_topics_track` (`userid`, `topic_id`, `category_id`)
VALUES ('{$topic_id}', '{$category_id}', '{$userid}')
END;

A faster alternative would be to have a UNIQUE INDEX on userid and topic_id.
CREATE UNIQUE INDEX forum_topics_track_ndx ON forum_topics_track(userid, topic_id);
Then you could do
INSERT IGNORE INTO `forum_topics_track` (`userid`, `topic_id`, `category_id`)
VALUES ('{$topic_id}', '{$category_id}', '{$userid}');
which would always succeed (possibly doing nothing if the data already is there).
Or you could look into the ON DUPLICATE KEY UPDATE trick.

This is the wrong way to implement the logic. If you want each user and topic to appear in forum_topics_track one time, then have the database enforce the constraint. This is easy with a unique index or constraint:
create unique index unq_forum_topics_track_user_topic on forum_topics_track(user_id, topic_id);
Then, you can do an insert and ignore or handle the error:
INSERT INTO `forum_topics_track` (`userid`, `topic_id`, `category_id`)
VALUES ('{$topic_id}', '{$category_id}', '{$userid}')
ON DUPLICATE KEY UPDATE userid = VALUES(userid);
No IF is needed in the logic. In fact, using IF just invites problems due to race conditions and doesn't really guarantee anything in the database.

IF NOT EXISTS is a clause that is available to use in MS-SQL but not in MySQL. Please try following query.
INSERT INTO `forum_topics_track` (`userid`, `topic_id`, `category_id`)
SELECT '{$topic_id}', '{$category_id}', '{$userid}'
WHERE NOT EXISTS(
SELECT * FROM `forum_topics_track` WHERE `userid` = '{$userid}' AND `topic_id` = '{$topic_id}'
)

Related

SQL: Unrecongnized statement near conditional (IF)

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

Insert with on duplicate key update gives error 1064

I'm trying to use this query but whatever I do I cannot get it to work. I'm still very new to the on duplicate key update syntax, but I can't find anything wrong with it
INSERT INTO product_leverancier (product_id, leverancier_id, prijs)
SELECT i.product_id, i.leverancier_id, i.prijs FROM import_tbl i
ON DUPLICATE KEY UPDATE product_id=VALUES(product_id),
leverancier_id=VALUES(leverancier_id), prijs=VALUES(prijs)
The error I get is this:
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 'UPDATE product_id=VALUES(product_id), leverancier_id=VALUES(leverancier_id), pr' at line 2
Error code 1064.
And whatever I change it's always the same error and error code.
Any idea what the problem is?
Your syntax is a bit off, and I don't believe that VALUES is used when using a SELECT as the source of the insert. Instead, use that source table for the update values:
INSERT INTO product_leverancier (product_id, leverancier_id, prijs)
SELECT i.product_id, i.leverancier_id, i.prijs
FROM import_tbl i
ON DUPLICATE KEY UPDATE
product_id = i.product_id,
leverancier_id = i.leverancier_id,
prijs = i.prijs
Note that the alias i is required when referring to the columns in the source table.
Here is a good reference question which delves deeper into the syntax of ON DUPLICATE KEY UPDATE when it is used with INSERT INTO ... SELECT:
INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE
Have you tried this?
ON DUPLICATE KEY UPDATE
product_leverancier.product_id = i.product_id,
product_leverancier.leverancier_id = i.leverancier_id,
product_leverancier.prijs = i.prijs

SQL Query Error - If Else Statement

The following SQl query gives me the error:
IF EXISTS (SELECT * FROM comments WHERE user_id='2' AND course_id='1')
UPDATE comments SET page1='exists' WHERE user_id='2' AND course_id='1'
ELSE
INSERT INTO comments (user_id,course_id,page1) VALUES ('2','1','inserted')
" #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 'IF EXISTS (SELECT * FROM comments WHERE user_id='2' AND course_id='1') UPDATE co' at line 1 "
I'm sure the syntax is correct?!
Add a unique key covering user_id and course_id
Then just use
INSERT INTO comments (user_id,course_id,page1)
VALUES ('2','1','inserted')
ON DUPLICATE KEY UPDATE page1='exists'
Check this IF-statement syntax:
Try this:
IF EXISTS (SELECT * FROM comments WHERE user_id='2' AND course_id='1') THEN
UPDATE comments SET page1='exists' WHERE user_id='2' AND course_id='1';
ELSE
INSERT INTO comments (user_id,course_id,page1) VALUES ('2','1','inserted');
OR
As per me you have to make practice of BEGIN...END block as shown below.
IF EXISTS (SELECT * FROM comments WHERE user_id='2' AND course_id='1') THEN
BEGIN
UPDATE comments SET page1='exists' WHERE user_id='2' AND course_id='1';
END
ELSE
BEGIN
INSERT INTO comments (user_id,course_id,page1) VALUES ('2','1','inserted');
END
My above queries will work in Procedures(PL-SQL). If you want to use above query in SQL
then use below code:
Create a UNIQUE constraint on your user_id & course_id columns, if one does not already exist:
ALTER TABLE comments ADD UNIQUE (user_id,course_id);
Use INSERT ... ON DUPLICATE KEY UPDATE:
INSERT INTO comments (user_id,course_id,page1)
VALUES ('2','1','inserted')
ON DUPLICATE KEY UPDATE page1='exists'

mysql if exists giving error wrong syntax?

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

mysql error update or insert failing

I'm going blind here... can't seem to find the error in this SQL:
INSERT INTO sankt_groups_order (
parent_group_id,
child_group_id,
order
) VALUES (?,?,?)
ON DUPLICATE KEY UPDATE
order = ?
;
I am getting this error:
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 'order ) VALUES ('65',NULL,'3') ON DUPLICATE KEY UPDATE order = '3''
Next will this SQL do what I think? I need it to insert the whole row if missing and update order if it exists... I have an index making parent_group_id and child_group_id unique.
order is a reserved word in mysql, you'll have to escape it:
child_group_id,
`order`
^-- ^--- backticks to escape
) VALUES (?,?,?)
and yes, it should do what you think. If there's a unique/primary key violation, you'll only change the order field.