Insert into MySQL "on duplicate key update" syntax error - php

$sql = "INSERT INTO couponentries (itemid, coupon, MSISDN, channel, result)
VALUES ('".$itemid."','".$CouponCode."', '".$MSISDN."','".$channel."','".$status."')
ON DUPLICATE KEY UPDATE couponentries.result = VALUES('Invalid couponcode[ERR: Already exists]')";
I am trying to insert new item from PHP webform to MySQL database. If I insert a duplicate row I will make the result update to an error message. Here is my code. It keeps giving me a syntax error.
ERROR: Could not able to execute 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 ''Invalid couponcode[ERR: Already exists]')' at line 3

You are using a string literal to update your column - lose the values:
$sql = "INSERT INTO couponentries (itemid, coupon, MSISDN, channel, result)
VALUES ('".$itemid."','".$CouponCode."', '".$MSISDN."','".$channel."','".$status."')
ON DUPLICATE KEY UPDATE couponentries.result = 'Invalid couponcode[ERR: Already exists]'";
Obligatory side note:
Concatinating strings like this makes your code is vulnerable to SQL Injection attacks. You should probably look into Prepared Statements instead.

Related

PHP PDO Exception[42000] when Deleting and Inserting into table in one statement [duplicate]

This question already has answers here:
PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)
(7 answers)
Closed 8 months ago.
I'm trying to delete any existing rows with a specified column value if they exist and Insert a new row directly after in a single prepared statement. I have tried both binding param values and passing an array to execute();
$sql = "DELETE FROM table WHERE id = :id;
INSERT INTO table (col1,col2,col3,col4,col5) VALUES (:col1,:col2,:col3,:col4,:col5);";
I have also tried:
$sql = "DELETE FROM table WHERE id = ?;
INSERT INTO table (col1,col2,col3,col4,col5) VALUES (?,?,?,?,?);";
They work fine separately, but wont work in one statement. The exact error being thrown is:
PHP Fatal error: Uncaught PDOException: 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 'INSERT INTO ...
The syntax error is pointing to the start of the second statement, so is it possible that I'm not supposed to be running a delete and insert statement after each other? I only have one version of mysql/mariadb installed and it's always been up to date, and the syntax works in separate statements. Operating system is Windows.
#Don'tPanic commented a link with a good answer:
PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)
In my Database config model I had set the ATTR_EMULATE_PREPARES to false for some reason, and setting it to true fixed the issue and the statement executed just fine. The post in the link also advises to specify the encoding type in the dsn if you do choose to set the attribute to true.

Alternatives for insert ignore into for SQL server

i just switched over from a Mysql server to SQL server. But i just found out that INSERT INGORE INTO doesn't work with sql server.
Original code:
INSERT IGNORE INTO DATA_EXACT_INVENTORY_LOCATIONS (ID, Code, Opslaglocatie, Omschrijving, OpVoorraad)
VALUES ('$inventorylocationID','$inventorylocationsItemCode','$inventoryStorageLocationsCode','$inventorylocationsItemDescription','$inventorylocationsCurrenctStock')
I found out that i can use on duplicate key update, but the problem is that i have sql query's with upto 50 variables. So to use on duplicate key update would be alot of work. So what i was wondering is there a better alternative for INSERT IGNORE INTO that's is just plug and play so i don't have to write all variables again.
You can use not exists:
INSERT DATA_EXACT_INVENTORY_LOCATIONS (ID, Code, Opslaglocatie, Omschrijving, OpVoorraad)
SELECT ID, Code, Opslaglocatie, Omschrijving, OpVoorraad
FROM (VALUES ('$inventorylocationID', '$inventorylocationsItemCode', '$inventoryStorageLocationsCode', '$inventorylocationsItemDescription', '$inventorylocationsCurrenctStock')
) V(ID, Code, Opslaglocatie, Omschrijving, OpVoorraad)
WHERE NOT EXISTS (SELECT 1
FROM DATA_EXACT_INVENTORY_LOCATIONS deil
WHERE deil.id = v.id -- or whatever column gets the duplicate key
);
Alternatively, you could rewrite the code to use MERGE. The SELECT should work in both databases.
Let me also add that you should learn to use parameters. Munging query strings with constant values exposes your code to SQL injection attacks and to hard-to-debug syntax errors.

Insert a POINT() value in mysql using Fat Free Framework

I need to insert a POINT value into my MySQL table using Fat Free Framework. I was hoping to do this using the F3 Mapper, but I got the impression that is not possible.
So I tried to use $db-exec()
This is my current code, based on various searches here and on google.
$geopoint = "POINT($lat $long)";
$db->exec("INSERT INTO event_dates ('eventGeoPoint') VALUES ($geopoint)");
This throws an error:
PDOStatement: 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 '52.8583742))' at line 1
I have also tried
$db->exec("INSERT INTO event_dates ('eventGeoPoint') VALUES (GeomFromText($geopoint))");
Please tell me how to correctly insert a POINT() value into my database using Fat Free Framework, either the mapper or exec
You need to correct your INSERT statement, which you are mixed with UPDATE statement.
INSERT INTO mytable SET myGeoPoint = 'GeomFromText($geopoint)
should be
INSERT INTO mytable(myGeoPoint) values (GeomFromText($geopoint))
Also, you need to use Prepared Statement to avoid SQL Injection.
Searching on after #Ravi's comments I found the answer in this post.
I changed my statement to
$result= $db->exec("INSERT INTO mytable (GeoPoint) VALUES (PointFromText(CONCAT('POINT(',$lat,' ',$long,')')))");
And it works!

SQL Update a whole table with new data

I am running a query every 15 minutes to retrieve new data from an API and store this data in my database.
So every 15 minutes I would like to store the new data in the table and get rid of the all old data in that table.
I am currently using the following method:
$sql = "DELETE FROM self_user_follower
INSERT INTO self_user_follower (username, profile_picture, full_name, user_id, last_updated)
VALUES (:query_username, :query_profile_picture, :query_full_name, :query_user_id, :query_last_updated)";
But it gives me the following error:
Array
(
[0] => 42000
[1] => 1064
[2] => 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 self_user_follower (username, profile_picture, full_name, user_id, l' at line 2
)
query_error
Is this the best way to do it or is there a nicer and cleaner way to do this?
If you want to put two SQL queries into one statement string, you have to
separate them with a semi-colon (;)
use the function mysqli_multi_query which supports multiple queries.
Unless you have a very good reason, modify your code so that it executes each query separately. MySQLi offers transaction support if you need that.*
The reason why you need a separate function is instructive; as mentioned in the docs:
An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.
*: Actually, I'm not even sure the multi_query will execute both queries in the same transaction - I'm just guessing for your reason to use a multi-query.
Multiple statements should be terminated by semi colon
Try this
$sql = "DELETE FROM self_user_follower;
INSERT INTO self_user_follower
(username, profile_picture, full_name, user_id, last_updated)
VALUES (:query_username, :query_profile_picture, :query_full_name, :query_user_id,
:query_last_updated)";

PHP insert into SQL statement with several parameters [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 7 years ago.
i have a simple php INSERT INTO SQL statement that simply refuses to update several columns at once. i have no idea why but the following statement is acceptabel;
$sql = "INSERT INTO niceTable (first) VALUES ('Hello')";
however if i try to following
$sql = "INSERT INTO niceTable (first, last) VALUES ('Hello', 'You')";
it breaks down and throws the following error:
"Error updating record: 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 'desc) VALUES ('Hello', 'update')' at line 1"
I have checked the syntax, but it seems ok. I am using a one.com server. Anyone got any tips?
Your actual query (not the one in your question) seems different. The error message seems to have desc somewhere, which is a reserved word. If you use reserve words as column names (don't), you should enclose them in backticks:
INSERT INTO tbl (`order`, `desc`) VALUES ('foo', 'bar');
As per your "posted code":
The reason being that first and last are MySQL reserved words
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
and require special attention.
Either wrap them in ticks or rename them to something other than reserved keywords.
INSERT INTO niceTable (`first`, `last`)
Edit: However, your error doesn't support the issue here, nor the column name(s):
for the right syntax to use near 'desc)
this tells me you are using desc which is also another MySQL reserved word.
You should also use prepared statements
https://en.wikipedia.org/wiki/Prepared_statement
Plus, should your inputs contain characters that MySQL may complain about such as apostrophes John O'Neil then you will need to escape those values.
MySQL will interpret that as ('Hello', 'John O'Neil') in turn causing another syntax error.
Escaping it, would interpret it as ('Hello', 'John O\'Neil') making it valid.
I'm thinking ahead here.
Enclose your column names in backticks
Last is a function in MySQL
$sql = "INSERT INTO niceTable (`first`, `last`) VALUES ('Hello', 'You')";

Categories