I'm getting MySQL error 42000:1064 that suggests a general syntax error with the following SQL:
UPDATE `events` SET ?=?, ?=?, ?=now() WHERE `event_id`=?;
PHP code to convert to a readable statement & also execute:
<?php
$ar = array_fill(0,count($args),'/\?/');
echo preg_replace($ar,$args,$sql,1);
$this->execute($sql, $args);
?>
This evaluates to:
UPDATE `events` SET event_name=test, form_id=webform, last_updated=now() WHERE `event_id`=124;
Which when pasted into the MySQL workbench completes successfully.
[mysqlErrorMsg] => 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 ''event_name'='test', 'form_id'='webform', 'last_updated'=now() WHERE `event_id`=' at line 1
It should be noted that my user has full access to the table in question.
You can't use placeholders on column names. Only on values.
Your query does NOT evaluate to (as it should)
UPDATE `events` SET event_name=test, form_id=webform, last_updated=now()
WHERE `event_id`=124;
but is being evaluated as this instead:
UPDATE `events` SET 'event_name'='test', 'form_id'='webform', 'last_updated'=now()
WHERE `event_id`=124;
See the quotes? These are strings, not column names.
So hard code the column names and only use placeholders for values
UPDATE `events` SET event_name=?, form_id=?, last_updated=now() WHERE `event_id`=?;
Related
I am trying to alter the auto_increment by laravel stament function and it is giving the error.
The complete error message displaying is 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 '?' at line 1 (SQL: alter table bills AUTO_INCREMENT=9)
if($quantity[$i]>$qtny)
{
Bills::where('id','=',$invoice_no)->delete();
DB::enableQueryLog();
DB::statement('alter table `bills` AUTO_INCREMENT=?',array('invoice_no'=>$invoice_no));
dd(DB::getQueryLog());
//return "<script>alert('Quantity is not available for product ".$item_name[$i]."');location.href='/create';</script>";
}
Variable Placeholder is not allowed here.
So. I have done by this way,
DB::statement('alter table `bills` AUTO_INCREMENT = '.$invoice_no);
Variable placeholders are not allowed everywhere:
Within the statement, ? characters can be used as parameter markers to indicate where data values are to be bound to the query later when you execute it.
alter table requires a constant here, e.g. you could not use something like alter table bills AUTO_INCREMENT = (select max(id) from bills). Generally, everywhere you could do this, you are allowed to use placeholders (with some exceptions like limit, but those are then mentioned in the documentation).
So in this case you have to use the value directly:
DB::statement('alter table `bills` AUTO_INCREMENT = '.$invoice_no)
You can write the laravel query in two diffrent way you can tokenize variable
1) First method
if($quantity[$i]>$qtny)
{
Bills::where('id','=',$invoice_no)->delete();
DB::enableQueryLog();
DB::statement('alter table `bills` AUTO_INCREMENT=:invoice_no',array('invoice_no'=>$invoice_no));
dd(DB::getQueryLog());
//return "<script>alert('Quantity is not available for product ".$item_name[$i]."');location.href='/create';</script>";
}
2) Second method
if($quantity[$i]>$qtny)
{
Bills::where('id','=',$invoice_no)->delete();
DB::enableQueryLog();
DB::statement('alter table `bills` AUTO_INCREMENT=?',[$invoice_no]);
dd(DB::getQueryLog());
//return "<script>alert('Quantity is not available for product ".$item_name[$i]."');location.href='/create';</script>";
}
You can also write query below but your query will be wide open for sql injection.
DB::statement('alter tablebillsAUTO_INCREMENT = '.$invoice_no);
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 6 years ago.
When I try to insert data where with code:
$query = dbConnect()->prepare("INSERT INTO users(key) WHERE mail='$mail' VALUES ('$key')");
I'm using XAMPP, it gives me an 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 'key) WHERE mail='maciej#localhost' VALUES (key)' at line 1 in C:\xampp\htdocs\PHP7_login\restore\index.php:38
You should use backticks for key (because is a reserved word)
and not use where
"INSERT INTO users(`key`) VALUES ('$key')"
or if you need an update
"UPDATE users
set `key` = '$key'
where mail = '$mail'"
The guess is that you want update:
update users
set key = '$key'
where mail = '$mail' ;
You should also learn to use parameters for values in queries. Substituting strings into the query string introduces the possibility of unexpected errors and makes the code vulnerable to SQL injection attacks.
key column in table is char(36) utf8_general_ci
//save no problem
$key_Ad= Yii::app()->db->createCommand('select UUID()')->queryScalar();
$modelAd->key=$key_Ad;
$modelAd->save()
//but problem in find
$post=Ad::model()->find( "key = :key",array(':key'=>$key_Ad) );
---------------------->Error
CDbException
CDbCommand failed to execute the SQL statement: 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 'key = '3f837af1-8a16-11e4-b111-00241d5e096e' LIMIT 1' at line 1. The SQL statement executed was: SELECT * FROM ad t WHERE key = :key LIMIT 1 (C:\xampp\htdocs\framework\db\CDbCommand.php:543)
0 C:\xampp\htdocs\framework\db\CDbCommand.php(415): CDbCommand->queryInternal('fetch', Array, Array)#1 C:\xampp\htdocs\framework\db\ar\CActiveRecord.php(1351): CDbCommand->queryRow()#2 C:\xampp\htdocs\framework\db\ar\CActiveRecord.php(1456): CActiveRecord->query(Object(CDbCriteria))#3 C:\xampp\htdocs\agahi\protected\controllers\ImageController.php(34): CActiveRecord->find('key = :key', Array)#4 C:\xampp\htdocs\framework\web\actions\CInlineAction.php(49): ImageController->actionUploadImage()#5 C:\xampp\htdocs\framework\web\CController.php(308): CInlineAction->runWithParams(Array)#6 C:\xampp\htdocs\framework\web\CController.php(286): CController->runAction(Object(CInlineAction))#7 C:\xampp\htdocs\framework\web\CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)#8 C:\xampp\htdocs\framework\web\CWebApplication.php(282): CController->run('UploadImage')#9 C:\xampp\htdocs\framework\web\CWebApplication.php(141): CWebApplication->runController('image/UploadIma...')#10 C:\xampp\htdocs\framework\base\CApplication.php(180): CWebApplication->processRequest()#11 C:\xampp\htdocs\agahi\index.php(13): CApplication->run()#12 {main}
The problem is that you have used the reserved mySql keyword 'key' as your column name. That's what generates the syntax error. It is best that you rename your column to something different than 'key', e.g. 'key1' or 'key_ad'.
In mySql you can still execute the query with the column named 'key' by escaping it in the select statement using '`', I'm not sure if you can do this in Yii, you should try it.
But the best solution is to just rename the column and not use reserved words as column names in the future.
I'm doing:
$truncateSQL = 'TRUNCATE TABLE :tableName';
$stmtTruncate = $em->getConnection()->prepare($truncateSQL);
$stmtTruncate->bindValue('tableName',$this->tableName);
$stmtTruncate->execute();
But getting the error:
[PDOException]
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 ''image_sizes_t'' at line 1
Are the quotes round the table name the problem here? $this->tableName is just a string
You can't use table or column names in as placeholders in prepared statements as 'table_name' is invalid MySql syntax.
if you need to make your column / table names safe you can wrap them in backticks.
"`".$table_name."`"
I have this query:
$query = "INSERT INTO users (users_uuid, type_id) VALUES (UUID_SHORT(), :type_id)";
My question is if in case the UUID_SHORT() generated already exists, is there any way to tell MySQL to generate another UUID_SHORT() within that query? What I have in my mind now is to trap the return error response then execute again the query, which I find inefficient.
Based #eicto comment, I read ON DUPLICATE KEY UPDATE then tried to reconstruct my query, I achieve a new query:
$query = "INSERT INTO users (users_uuid, type_id) VALUES (UUID_SHORT(), :type_id) ON DUPLICATE KEY UPDATE (users_uuid) = VALUES(UUID_SHORT())";
However I received an error in my log that states:
"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 '(users_uuid) = VALUES(UUID_SHORT())' at line 1"
What does this mean?