syntax error in ON UPDATE DUPLICATE KEY? - mysql

I was trying to use the ON UPDATE DUPLICATE KEY clause for the first time, following this link
SQL - IF EXISTS UPDATE ELSE INSERT INTO
and I'm getting an error in my sql syntax:
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 ''AJAY KUMAR')'
at line 2 The SQL being executed was: INSERT INTO fee_acc_balance
(guardian_name, account_no, paid_amount, due, days_overdue,
total_fees, updated_on) VALUES ('AJAY KUMAR', '10', 0, 12550, 0,
12550, '2017-02-10 21:28:05') ON DUPLICATE KEY UPDATE guardian_name =
VALUES ('AJAY KUMAR') Error Info: Array ( [0] => 42000 [1] => 1064 [2]
=> You have an error..
The unique key in my case is account_no, and this is my sql :
INSERT INTO fee_acc_balance (guardian_name, account_no, paid_amount, due, days_overdue, total_fees, updated_on)
VALUES ('$father_name', '$account->account_no', $payments, $sum, 0, $sum,'$now')
ON DUPLICATE KEY UPDATE guardian_name = VALUES ('$father_name')
Where does the error lie?

You cannot specify an absolute value in ON DUPLICATE KEY UPDATE:
ON DUPLICATE KEY UPDATE guardian_name = VALUES ('$father_name')
Try with
ON DUPLICATE KEY UPDATE guardian_name = VALUES(guardian_name)
Notice that the right part of the assignment is the new field coming in from VALUES, and the left side is the extant record; "UPDATE a = VALUES(a)" means "put the a from VALUES into the record", not "leave everything as it is".
Also, you may want to write variables in curly brackets:
...VALUES ('{$father_name}', '{$account->account_no}', {$payments}, {$sum}, 0, {$sum}, '{$now}')
or even better use PREPAREd statement with PDO:
$stmt->prepare("INSERT... VALUES(?, ?, ?, ?, 0, ?, ?)");
$stmt->execute([
$father_name,
$account->account_no,
$payments,
$sum,
$sum,
$now
]);
and, better still, bound parameters.
Otherwise, strange things might happen if the guardian name is Ajay Al'Kumar (note the quote mark) or a string value is passed instead of an integer one.

Related

How to use `CONCAT` in a `UPDATE`

I´m trying to use CONCAT in a mysql UPDATE.
"INSERT INTO table (
objekt_nr,
objekt_status)
VALUES(
:objekt_nr,
'salj,$fakt')
ON DUPLICATE KEY UPDATE
objekt_status = VALUES(CONCAT(objekt_status, 'salj,$fakt'))";
$query_params = array(
':objekt_nr' => $_POST['objekt_nr']);
I have tried several:
objekt_status = VALUES(CONCAT(objekt_status, objekt_status))";
objekt_status = VALUES(CONCAT(objekt_status, 'addMe'))";
objekt_status = VALUES(CONCAT(objekt_status, 'salj,$fakt'))";
objekt_status = VALUES((CONCAT(objekt_status, 'salj,$fakt')))";
Error Code for:
objekt_status = VALUES(CONCAT(objekt_status, 'salj,$fakt'))";
...syntax to use near '(objekt_status, 'salj,fakt,'))'
How should the code look like?
You have an semicolon where there should be a comma (after VALUES(objekt_nr);), and it appears the apostrophe is in the wrong place on the last line at $fakt. VALUES is only required for the INSERT, manual here
This query should be correct:
"INSERT INTO table (
objekt_nr,
objekt_status)
VALUES(
:objekt_nr,
'salj,$fakt')
ON DUPLICATE KEY UPDATE
objekt_nr = objekt_nr,
objekt_status = CONCAT(objekt_status, 'salj,$fakt')";
Also please ensure your variables are escaped, or use a prepared statement.
Try removing values as well as semicolon from the query
"INSERT INTO table (
objekt_nr,
objekt_status)
VALUES(
:objekt_nr,
'salj,$fakt')
ON DUPLICATE KEY UPDATE
objekt_nr = objekt_nr,
objekt_status = CONCAT(objekt_status, 'salj,'$fakt)";
Actually in my case i needed the "Values" for every line but the CONCAT line.
objekt_created_when = VALUES(objekt_created_when),
objekt_status = CONCAT(objekt_status, 'salj,$fakt') ";
If i did remove VALUES from all rows, values in db, got empty!

Nodejs mysql ON DUPLICATE KEY UPDATE

I'm using Node Mysql
var values = []; //array with actual values
var sql = "INSERT INTO table (field1, field2) VALUES ? ON DUPLICATE KEY UPDATE updated_at = now()";
connection.query(sql, values, function() {
});
And I get 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
'ON DUPLICATE KEY UPDATE updated_at = now()
Meanwhile the same query works in mysql cli.
What could be the problem?
You are not placing any value on the "values" array, and the INSERT expects two. You can check how the SQL got built with:
var query = connection.query(sql, values, function() {});
console.log(query.sql);

ERROR 1064 (42000) - MySQL error in INSERT ... SELECT query

As part of a MySQL trigger I'm writing, I've got an INSERT ... SELECT query that is returning :
ERROR 1064 (42000) at line 7: 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 'pp2 (curr_code, pricing_id, pid, title, startdate, enddate, priority, enabled) S' at line 33
INSERT INTO product_pricing pp2 (curr_code, pricing_id, pid, title, startdate, enddate, priority, enabled)
SELECT cc, `pp1`.`pricing_id`, `pp1`.`pid`, `pp1`.`title`, `pp1`.`startdate`, `pp1`.`enddate`, `pp1`.`priority`, `pp1`.`enabled`
FROM product_pricing pp1
WHERE pp1.pp_id = NEW.pp_id
ON DUPLICATE KEY UPDATE pp2.pp_id=(SELECT newppid := pp2.pp_id);
I'm not sure if it's the cc part? That's a declared variable in the trigger but it should work given that you should be able to do a SELECT 'hello', t.col1 FROM table t
Any suggestions as to what the error is greatly received.
The INSERT syntax doesn't allow for aliases.
INSERT INTO table [ ( column [, ...] ) ]
{ DEFAULT VALUES | VALUES ( { expression | DEFAULT } [, ...] ) [, ...] | query }
[ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]
Remove that pp2 from the INSERT query

working perl ascript now says .DBD::mysql::db do failed: You have an error in your SQL syntax;

I got this perl script and it used to work fine till recently.
i am getting this error message.
DBD::mysql::db do failed: 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 ' '')
ON DUPLICATE KEY UPDATE value=''' at line 2 at import_productfeatures.pl line 71.
DBD::mysql::db do failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL serve r version for the right syntax to use near ' '')
ON DUPLICATE KEY UPDATE value=''' at line 2 at import_productfeatures.pl line 71.
foreach my $feature (#features) {
my $cat_featureid = $feature->{CategoryFeature_ID};
my $value = $feature->{Presentation_Value};
my $sql = "INSERT INTO products_features (product_id, feature_id, value)
VALUES (".$prodid.", ".$cat_featureid.", ".$dbh->quote($value).")
ON DUPLICATE KEY UPDATE value=".$dbh->quote($value);
$dbh->do($sql);
}
You should use placeholders, instead of putting the values directly into the string:
my $sql = "INSERT INTO products_features (product_id, feature_id, value)
VALUES (?,?,?)
ON DUPLICATE KEY UPDATE value=?";
my $sth = $dbh->prepare($sql);
foreach my $feature (#features) {
my $cat_featureid = $feature->{CategoryFeature_ID};
my $value = $feature->{Presentation_Value};
$sth->execute($prodid,$cat_featureid,$value,$value);
}
$sth->finish();
DBI will handle the correct escaping for you.
Print out the value of $sql so you can see the SQL statement that you are building. Then you can see what the syntax problem is, or post it here so we can diagnose it.
However, even more than that, you should be using parametrized queries, not building SQL statements with untrusted external data. You are leaving yourself open to SQL injection. Please see http://bobby-tables.com/perl.html for examples on how to do it properly.
I think u missed single quote.
change
my $sql = "INSERT INTO products_features (product_id, feature_id, value)
VALUES (".$prodid.", ".$cat_featureid.", ".$dbh->quote($value).")
ON DUPLICATE KEY UPDATE value=".$dbh->quote($value);
to
my $sql = "INSERT INTO products_features (product_id, feature_id, value)
VALUES (".$prodid.", ".$cat_featureid.", '".$dbh->quote($value)."')
ON DUPLICATE KEY UPDATE value='".$dbh->quote($value."'");

Why CakePHP forms INSERT statement with 'CURRENT_TIMESTAMP' in quotes?

I'm getting this error, because cakephp 1.3.11 creates an INSERT statement with 'CURRENT_TIMESTAMP' in quotes. Similar thing worked in 1.3.9. What might I be doing wrong?
SQL Error: 1292: Incorrect datetime value: 'CURRENT_TIMESTAMP' for column 'time_posted' at row 1 [CORE\cake\libs\model\datasources\dbo_source.php, line 684]
This is the context query:
$sql = "INSERT INTO `my_table` (`time_posted`, `version`, `provider`, `date`) VALUES ('CURRENT_TIMESTAMP', 0, 'provider', '2011-08-03 16:11:00')"
I'm trying to create a new record in database from cakephp using this code:
class MyTable extends AppModel
{
...
function blah() {
...
$this->create()
$ret=$this->save(array('MyTable'=>array('provider'=>$provider,'date'=>$datetime)));
...
here's the stack:
DboSource::showQuery() - CORE\cake\libs\model\datasources\dbo_source.php, line 684
DboSource::execute() - CORE\cake\libs\model\datasources\dbo_source.php, line 266
DboSource::create() - CORE\cake\libs\model\datasources\dbo_source.php, line 752
Model::save() - CORE\cake\libs\model\model.php, line 1342
MyTable::add() - APP\models\my_table.php, line 1288
As Dunhamzzz said, there must be a place causing CURRENT_TIMESTAMP to be inserted.
Once you find it, you can use date('Y-m-d H:i:s') to save using the current time.
Or, if you want to do it using SQL, you can use DboSource::expression('NOW()').
ie.
array('MyTable'=>array('time_posted' => DboSource::expression('NOW()')))