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.
I have this code:
try {
$sql = "INSERT INTO order(
user_id,
departure_street,
departure_housenr,
departure_postalcode,
departure_city,
arrival_street,
arrival_housenr,
arrival_postalcode,
arrival_city,
order_date,
lifter,
order_status
)
VALUES(
:user_id,
:departure_street,
:departure_housenr,
:departure_postalcode,
:departure_city,
:arrival_street,
:arrival_housenr,
:arrival_postalcode,
:arrival_city,
:order_date,
:lifter,
:order_status
)";
$stmt = $dbh -> get_instance() -> prepare( $sql );
$stmt -> execute( array( ':user_id' => $_SESSION[ 'user_id' ],
':departure_street' => $street1_parsed,
':departure_housenr' => $streetnumber1,
':departure_postalcode' => $postcode1,
':departure_city' => $city1_parsed,
':arrival_street' => $street2_parsed,
':arrival_housenr' => $streetnumber2,
':arrival_postalcode' => $postcode2,
':arrival_city' => $city1_parsed,
':order_date' => $datetime,
':lifter' => $lifter,
':order_status' => $order_status ) );
}
catch( PDOException $e ) {
echo $e -> getMessage() . '<br />' . $sql;
}
This code keeps giving me 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(
user_id,
departure_street, ' at line 1
I don't understand what can be wrong with the syntax. I've used this query so many times and it always works. What's the problem now? I've tried to echo the $sql variable to see what the resulting query looks like, but it doesn't show me the values that are being inserted. Can anyone see the SQL syntax error?
ORDER is mysql key word .it should be enclosed by backticks .if your table name or column name is key word just use backticks order backticks ``
here you can find the mysql keywords list
Related
This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 8 years ago.
I have a table with hyphens in the name, and I can't change the table name so I thought backticks would help.
Unfortunally for me it failed, some googling did'nt give me any answers. How can I solve this?
ex:
$stmt = $this->_dbh->prepare(
'UPDATE `:table`
SET status = NOT status
WHERE id=:id;');
$stmt->bindParam(':table',$this->_settings['table'], PDO::PARAM_STR);
$stmt->bindParam(':id',$data['id'], PDO::PARAM_INT);
if( $stmt->execute() ){
return 'Success';
}
else{
$this->_log( $stmt->errorInfo() );
return 'Action failed.';
}
In the log, with backticks:
13:25:18 42S02
1146
Table 'db_name.'table-name'' doesn't exist
Without backticks:
13:38:14 42000
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 ''table-name'
SET status = NOT status
WHERE id='1'' at line 1
If you need to inject the table name, you can't do it as a bind variable; as long as the value has been whitelisted, you can use
$stmt = $this->_dbh->prepare(
sprint(
'UPDATE `%s`
SET status = NOT status
WHERE id=:id;',
$this->_settings['table']
)
);
$stmt->bindParam(':id',$data['id'], PDO::PARAM_INT);
This question already has answers here:
How can I write SQL for a table that shares the same name as a protected keyword in MySql? [duplicate]
(3 answers)
Closed 9 years ago.
I have problem with PDO and can't find the solution:
My function:
public static function create($position, $name, $mail, $mailtext, $confirmed, $key, $formid) {
global $database;
try {
$pdo_result = $database->prepare('INSERT INTO Form (Position, Name, Mail, MailText, Confirmed, Key, Form_idForm) VALUES(:Position, :Name, :Mail, :MailText, :Confirmed, :Key, :Form_idForm)');
$pdo_result->execute(array(
':Position' => $position,
':Name' => $name,
':Mail' => $mail,
':MailText' => $mailtext,
':Confirmed' => $confirmed,
':Key' => $key,
':Form_idForm' => $formid
));
return $database->lastInsertId();
} catch(PDOException $e) {
Page::error('Error: Message:', $e->getMessage());
}
return null;
}
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 'Key, Form_idForm) VALUES('Position', 'Name', 'Mail', 'MailText', '1', 'keeey', '' at line 1
You're using reserved words in your field names.
Try escaping your INSERT-statement within your $database->prepare-construct like this:
INSERT INTO Form (
`Position`, `Name`, `Mail`, `MailText`,
`Confirmed`, `Key`, `Form_idForm`) ....
Eventually because of the use of Key, a preserved MySQL word.
Use another word instead or use backtick `.
by: https://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
You can still use key if you want to. Just wrap it with backtick,
INSERT INTO Form (
`Position`, `Name`, `Mail`, `MailText`,
`Confirmed`, `Key`, `Form_idForm`)
but as an advise, refrain from using any reserved keyword to avoid future problems. :)
MySQL Reserved Keywords List
key is a keyword in SQL. You can therefore not use it as a column name.
You should rename it, else it will cause issues like the one you are currently experiencing.. however you can "escape" the field names like so which will also rectify this issue:
INSERT INTO Form (`Position`, `Name`, `Mail`, `MailText`, `Confirmed`, `Key`, `Form_idForm`) VALUES(:Position, :Name, :Mail, :MailText, :Confirmed, :Key, :Form_idForm)');
You can find a full list of reserved words here: http://dev.mysql.com/doc/refman/5.0/en/reserved-words.html
I am trying to insert some values in the table the query is below:
Insert into
auditlog (
event,
desc,
userid,
useripaddress,
audittype
)
VALUES (
'User Authenticated',
'Useradminsuccessfully logged in to the system',
'1',
'127.0.0.1','1'
)
It gives me the following error:
#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 'desc,userid,useripaddress,audittype)VALUES ('User Authenticated', 'User admin su' at line 1
However when i run the insert using PHPMYAdmin it does insert a value and the query generated is
INSERT INTO
`auditlog`(
`event`,
`desc`,
`userid`,
`useripaddress`,
`audittype`)
VALUES (
'User Authenticated',
'Useradminsuccessfully logged in to the system',
'1',
'127.0.0.1','1'
)
The only difference i see is the quotes which i dont believe are needed. I don't understand where am i going wrong and am breaking my head now :):)
The backticks are needed around desc because it is a reserved word.
INSERT INTO auditlog (event, `desc`, userid, useripaddress, audittype)
VALUES (
'User Authenticated',
'Useradminsuccessfully logged in to the system',
'1',
'127.0.0.1',
'1'
)
There is also no harm in adding backticks around the other column names if you aren't sure whether or not they are reserved words.
Here is a list of words that are reserved and needs to be backticked: http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html
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.
I've looked through all the other StackOverflow (and google) posts with the same problem, but none seemed to address my problem.
I am using PDO and PHP.
My code:
$vals = array(
':from' => $email,
':to' => $recipient,
':name' => $name,
':subject' => $subject,
':message' = >$message
);
print_r($vals);
try {
$pdo = new PDOConfig();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM messages WHERE `message` LIKE :message";
$q = $pdo->prepare($sql);
$q->execute(array(':message' => $vals[':message']));
$resp = $q->fetchAll();
foreach ($resp as $row) {
throw new Exception('Please do not post the same message twice!');
}
$sql = "INSERT INTO messages (from, to, name, subject, message) VALUES (:from, :to, :name, :subject, :message)";
$q = $pdo->prepare($sql);
$q->execute($vals);
}
catch(PDOException $e) {
echo $e->getMessage();
}
and the first print_r gives
Array ( [:from] => abc#gmail.com
[:to] => lala#me.com
[:name] => abc
[:subject] => abc
[:message] => abc )
which is expected (none are null)
but it outputs the 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 'from, to, name, subject, message) VALUES ('abc#gmail.com', 'lala#me.com' at line 1
No idea how to fix this. any ideas?
from is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`.
Personally, I wouldn't bother; I'd just rename the column.
PS. as pointed out in the comments, to is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at drupal.org maintain a list of reserved words in SQL.
I've got this exact error, but in my case I was binding values for the LIMIT clause without specifying the type. I'm just dropping this here in case somebody gets this error for the same reason. Without specifying the type LIMIT :limit OFFSET :offset; resulted in LIMIT '10' OFFSET '1'; instead of LIMIT 10 OFFSET 1;. What helps to correct that is the following:
$stmt->bindParam(':limit', intval($limit, 10), \PDO::PARAM_INT);
$stmt->bindParam(':offset', intval($offset, 10), \PDO::PARAM_INT);
ALTER TABLE `{$installer->getTable('sales/quote_payment')}`
ADD `custom_field_one` VARCHAR( 255 ) NOT NULL,
ADD `custom_field_two` VARCHAR( 255 ) NOT NULL;
Add backtick i.e. " ` " properly. Write your getTable name and column name between backtick.
Same pdo error in sql query while trying to insert into database value from multidimential array:
$sql = "UPDATE test SET field=arr[$s][a] WHERE id = $id";
$sth = $db->prepare($sql);
$sth->execute();
Extracting array arr[$s][a] from sql query, using instead variable containing it fixes the problem.
I have function that updates log table.
function wslog($userID, $log, $where) {
safe_query("INSERT INTO ".PREFIX."log ( time, userID, log, where ) values( '".time()."', '".$userID."', '".$log."', '".$where."' ) ");
}
And I have this php code:
wslog($userID, 'server|'.mysql_insert_id().'', 'servers');
But I keep getting syntax error:
Query failed: errorno=1064
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 'where ) values( '1269208030', '1', 'server|14', 'servers' )' at line 1
query=INSERT INTO ws_DII_log ( time, userID, log, where ) values( '1269208030', '1', 'server|14', 'servers' )
Is it possible that SQL doesn't like your log field name as it is a reserved word?
If so, try putting it is backticks
log ( `time`, `userID`, `log`, `where` )