Invalid PDO MySQL Statement - Error in Syntax - php

So, I have the following PDO statement, which is one of several similarly constructed statements on the page. The rest are working fine, so I am confused as to why this one is stating invalid syntax.
$test_id = '1';
$option = 'a';
$ab_email = 'test#testing.com';
$stmt = $pdo_db->prepare("INSERT INTO `ab_tests_visitors` (test_id,option,visits,email) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE email=?");
$stmt->execute(array($test_id,$option,1,$ab_email,$ab_email));
The schema for the database has 5 columns, 2 of which are indexes.
visitor_id is int(10) and auto_increment, and also primary
test_id is int(10)
option is varchar(100)
visits is int(10) and default of 1
email is varchar(255) and unique
The error being given is:
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 MySQL server version for the right syntax to use near 'option,visits,email) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE email=?' at line 1'

option is a MySQL keyword. If you want to use it as an identifier, make sure to always surround it with backticks (as you should do with identifiers anyway):
$stmt = $pdo_db->prepare("INSERT INTO `ab_tests_visitors` (`test_id`,`option`,`visits`,`email`) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE `email`=?");

For this problem, in name of your column, you must use backticks ` around the column name (alt + 96)

Related

Syntax error or access violation: 1064 You have an error in your SQL syntax in alter table

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);

CakePHP2.x got syntax error when use Prepared Statement by query() method

I'm using CakePHP 2.9.9.
I want to use prepared statement in query method, but got syntax error.
code is below
$query = 'CREATE TABLE IF NOT EXISTS ? (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY)';
$this->User->query($query, array('dynamic_table_name'));
error message is 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 ''dynamic_table_name' (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY)' at line 1
Why escape by single quote like ''dynamic_table_name' ?
How to fix it?

How to fix SQLSTATE[42000] error; using prepared statements

I'm trying to create an email confirmation script.
Here is my PHP code:
...
$q = $dbh->prepare("INSERT INTO `email_confirm` (UserID,token,tokenDate) VALUES(:id, :token, UTC_TIMESTAMP()) ON DUPLICATE KEY UPDATE token = VALUES(:token), tokenDate = UTC_TIMESTAMP();");
$result = $q -> execute( array( ":id" => $this->id, ":token" => $token ) );
...
When this runs, I receive the following error:
Caught exception: 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 '?), tokenDate = UTC_TIMESTAMP()' at line 1
I'm no expert in MySQL, but I couldn't find any syntax errors in my code, and I would love some help.
As documented under PDO::prepare:
You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute(). You cannot use a named parameter marker of the same name more than once in a prepared statement, unless emulation mode is on.
Whilst you could add a :token2 placeholder or similar that happens to be bound to the same value, actually MySQL's VALUES() function in the ON DUPLICATE KEY UPDATE clause takes a column name not a literal. Therefore this will do the trick:
$q = $dbh->prepare('
INSERT INTO email_confirm
(UserID, token, tokenDate)
VALUES
(:id, :token, UTC_TIMESTAMP())
ON DUPLICATE KEY UPDATE
token = VALUES(token),
tokenDate = UTC_TIMESTAMP()
');
However, you may want to look into Automatic Initialization and Updating for TIMESTAMP and DATETIME, rather than trying to reimplement the wheel.

Symfony DBAL insert gives: "Syntax error or access violation: 1064"

I'm trying to insert some data into database, but something is off here. Cannot catch what it is and I'm hoping someone might be able to tell me what's going on with this one.
My table looks somewhat like this:
CREATE TABLE IF NOT EXISTS `db_name`.`order` (
`orderID` INT NOT NULL AUTO_INCREMENT,
`order_ordernumber` VARCHAR(200) NOT NULL,
`order_orderweight` INT NOT NULL,
... And other columns as well, but all NULL
ENGINE = InnoDB
I'm using Symfony2-framework and it's DBAL-insert here:
$conn->insert('order', array(
'order_ordernumber' => $this->orderid,
'order_orderweight' => $this->totalweight
));
"$this->orderid" is string variable, and "$this->totalweight" is int.
And it gives this error-message:
An exception occurred while executing 'INSERT INTO order (order_ordernumber, order_orderweight) VALUES (?, ?)' with params ["000001", 900]:
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 (order_ordernumber, order_orderweight) VALUES ('000001', '900')' at line 1
500 Internal Server Error - DBALException
1 linked Exception: PDOException ยป
I can do the same query on pure sql and it works, this one doesn't. What on earth is going on with this one?
order is a reserved keyword in MySQL : http://dev.mysql.com/doc/refman/5.6/en/reserved-words.html
You have to use backquotes arround the word to prevent this error. But a better recommendation would be to prefix your table.

save and find uuid by mysql and yii

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.

Categories