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
Related
This question already has answers here:
PDO Parameterized Query - Reuse named placeholders?
(5 answers)
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 3 years ago.
I'm trying to write a query to insert/update a table and it's my first time using prepared statements, I'm receiving the error SQLSTATE[HY093]: Invalid parameter number but from what I can see I'm passing all the columns/values required.
(I'm trying to do this without using bindParam as in example #2 here)
This is just a test for now, I plan on making it dynamic once I've actually got a query working.
$data_test = [
':event_id' => 3354,
':event' => 'TESTESTEST',
':staff_booking_id' => 27255,
':is_read' => 'yes',
':priority' => 'medium'
];
$q = "INSERT INTO events(event_id, event, staff_booking_id, is_read, priority)
VALUES(:event_id, :event, :staff_booking_id, :is_read, :priority)
ON DUPLICATE KEY UPDATE event_id = LAST_INSERT_ID(:event_id), event = :event, staff_booking_id = :staff_booking_id, is_read = :is_read, priority = :priority;";
$result = $this->db->prepare($q);
$result = $result->execute($data_test);
As commentented by FunkFortyNiner and tadman, it is possible that the issue comes from the fact that you are reusing the same placeholder.
Actually the MySQL syntax does not require you to reuse the named parameter: you can use the VALUES() to refer to the values initially passed for INSERT.
Also, your attempt to update event_id using LAST_INSERT_ID() does not seem right; I am unsure that this is valid syntax - and anyway, if this is the primary key of table, then you don't want to update it.
Finally, as pinpointed by FunkFortyNiner, event is a reserved word in MySQL, so it needs to be quoted.
$q =
"INSERT INTO events(
event_id,
`event`,
staff_booking_id,
is_read,
priority
)
VALUES(
:event_id,
:event,
:staff_booking_id,
:is_read,
:priority
)
ON DUPLICATE KEY UPDATE
`event` = VALUES(`event`),
staff_booking_id = VALUES(staff_booking_id),
is_read = VALUES(is_read),
priority = VALUES(priority)";
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
I am trying to add two simple strings and one date to a SQL Server using PDO in PHP. I'm currently using the following code to do so:
$data = array(
'Omschrijving' => 'Mijn mooie omschrijving...',
'Toelichting' => 'Mijn leuke toelichting...'
);
# Insert data
$STH = $DBH->prepare("INSERT INTO memo (Datum, Omschrijving, Toelichting) VALUES (NOW(), :Omschrijving, :Toelichting)");
$STH->execute($data);
It works perfectly without the date, but for some reason it gives me the following error when I try to add the date:
SQLSTATE[42000]: Syntax error or access violation: 8180 [FreeTDS][SQL Server]Statement(s) could not be prepared. (SQLExecute[8180] at /builddir/build/BUILD/php-5.6.9/ext/pdo_odbc/odbc_stmt.c:254)
Does anyone know what I'm doing wrong?
Thanks in advance!
Now() is a MySQL function. GetDate() is the sql-server's equivalent. Here's their documentation on the function, https://msdn.microsoft.com/en-us/library/ms188383.aspx.
So provided code should become:
$data = array(
'Omschrijving' => 'Mijn mooie omschrijving...',
'Toelichting' => 'Mijn leuke toelichting...'
);
# Insert data
$STH = $DBH->prepare("INSERT INTO memo (Datum, Omschrijving, Toelichting) VALUES (GETDATE(), :Omschrijving, :Toelichting)");
$STH->execute($data);
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.