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);
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 answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
I'm using MySQLiIn the WHERE clause of my statement I am adding parameters on RHS:
Prepared statement:
$sql = 'select * from emailstobeverified where email=email_input and verification_code=code_input;';
And then I use $stmt->prepare($sql);
And I get a PHP error saying:
Sql Error: Unknown column 'email_input' in 'where clause'
(I thought that the LHS of the boolean expression counts as the column? )
the below query will work:
$sql = 'insert into emailstobeverified (email) values (:email);';
Here, I can use :email as a parameter, so I tried making email_input have a colon before it: :email_input and used that as the param. However I got a syntax error:
Sql Error: 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 ':email_input and verification_code=:code_input' at line 1
What's the correct syntax for comparing the table column value to some param?
Your syntax is off, and email_input should instead be a positional parameter:
$sql = "SELECT * FROM emailstobeverified WHERE email = ? and verification_code = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("si", $email_input, $code);
$stmt->execute();
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'm not a newbie to PHP but I have encountered a [seemingly] simple problem which I cannot figure out how to resolve.
MySQL throws error that the syntax is wrong.
My Statement is this:
if($value){
$query = "UPDATE ".$preuploads." SET words = '$words_amount' WHERE id= $sn_id";
$db->sql_query( $query ) or die( mysql_error() );
}
And then $words_amount is an integer, $sn_id is also an integer. They are double checked.
The statement when printed before execution is as follows:
UPDATE SET uploads words = '250' WHERE id= 8081
// edited, with the name of table added since the problem primarily was
// with the encapsulation and the name of table just was dropped in this question
// and not in the app
however words value ('250') is tested with integer data-type as well, but no change occurs and the error lingers on.
And the error thrown is:
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 'SET words = '250' WHERE id= 8081' at line 1
If I understand your question (and preuploads is a table), then
$query = "UPDATE ".$preuploads." SET words = '$words_amount' WHERE id= $sn_id";
should be
$query = "UPDATE ".$preuploads." SET words = '".$words_amount."' WHERE id=".$sn_id;
Or, even better prepare and use bind_param,
$stmt = $mysqli->prepare("UPDATE ? SET words=? WHERE id=?");
$stmt->bind_param($preuploads, $words_amount, $snd_id);
$stmt->execute();
check your string ($words_amount) has any single quotes ' if it is then remove it by using this option on php $words_amount=string_replace("'","/'",$your_string_variable);
I have found two errors:
First, not encapsulation of the data should occur, thus:
$words_count should be left as is, not to be encapsulated with '
And the table and fields name should be encapsulated with backtick
I think your having problem with name of table. The syntax for update query is
UPDATE table_name SET words = '250' WHERE id= 8081
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.