Using ON DUPLICATE KEY UPDATE in PDO [duplicate] - php

This question already has answers here:
PDO prepared statements for INSERT and ON DUPLICATE KEY UPDATE with named placeholders
(2 answers)
Closed 7 years ago.
How can I use ON DUPLICATE KEY UPDATE in PDO
My problem is that I get (SQLSTATE[42000]: Syntax error or access violation?) when I try the following synthaxe, the insert function and update works fine, but when I use both with on duplicate, I get error :
$query = "INSERT INTO my_table (name,tophtml,bothtml,lang,background_mode,redirhtml,bg_color)
VALUES (:name, :top_html, :bottom_html, :hs_language, :bg_style, :redirect_to, :bg_color )
ON DUPLICATE KEY UPDATE
tophtml= :top_html, bothtml= :bottom_html, lang= :hs_language, bg_color= :bg_color, redirhtml= :redirect_to, background_mode= :bg_style WHERE name=:name
";
$request = $databaseStatus->connection->prepare($query);
$request->bindParam(":name", $name, PDO::PARAM_STR);
$request->bindParam(":top_html", $top_html, PDO::PARAM_STR);
$request->bindParam(":bottom_html", $bottom_html, PDO::PARAM_STR);
$request->bindParam(":bg_color", $bg_color, PDO::PARAM_STR);
$request->bindParam(":redirect_to", $redirect_to, PDO::PARAM_STR);
$request->bindParam(":hs_language", $hs_language, PDO::PARAM_STR);
$request->bindParam(":bg_style", $bg_style, PDO::PARAM_STR);
$request->execute();

I found the solution here.
My problem was in the where clause, you don't need to put the table name or SET in the ON DUPLICATE KEY clause, and you don't need a WHERE clause (it always updates the record with the duplicate key).

Related

SQL- insert and update in the same method [duplicate]

This question already has answers here:
How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?
(7 answers)
Postgres on conflict do update on composite primary keys
(2 answers)
Closed 6 months ago.
I have a problem with my SQL statement written in PHP.
I am using store() function to both INSERT or UPDATE object in the database following it's rule that it can be done:
The INSERT OR UPDATE command is an extension of the INSERT command, with these differences:
If the row being inserted does not exist, INSERT OR UPDATE performs an
INSERT operation. If the row being inserted already exists, INSERT OR
UPDATE performs an UPDATE operation, updating the row with the
specified column values.
I wrote type declaration for the Content ID like : public ?$contentId = null; so I can use the same methods for both actions.
public function store(Content $content, int $teamId)
{
$rsm = new ResultSetMapping($this->entityServiceRepository);
$stmt = $this->entityServiceRepository->getConnection()->prepare(
'UPDATE content
SET
name = :name,
url = :url,
WHERE id = :contentId
AND team_id = :teamId
',
$rsm
);
$stmt->bindValue("contentId", $content->getId(), PDO::PARAM_INT);
$stmt->bindValue("teamId", $content, PDO::PARAM_INT);
$stmt->bindValue("name", $content->getName(), PDO::PARAM_STR);
$stmt->bindValue("url", $content->getUrl(), PDO::PARAM_STR);
$stmt->executeQuery();
However from some reason data does not exist in the database. All bindValue() return true ant other sql queries seems to work well. How can I debug this query? Or can someone tell is there a problem with sql query I wrote.
Thanks.

Prepared statements, SQLSTATE[HY093]: Invalid parameter number [duplicate]

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

How Insert now() function in MySQL using PHP [duplicate]

This question already has answers here:
Inserting NOW() into Database with CodeIgniter's Active Record
(11 answers)
Closed 7 years ago.
I'm trying to do an update in MySQL from PHP with CodeIgniter, but, how can I insert a now() method?
I mean, I'm using an array to insert my information, but, how can I insert the date?
This is an example of my array:
$data = array(
'name' => $inputName,
'lastname' => $inputLast,
'DOBirth' => now()
);
NOW() is part of MySQL, not PHP, so you need to put into the query.
Try this way, which is how you handle it using PDO. This should work:
$stmt = $pdoDb->prepare('INSERT INTO tablename (name, lastname, dobirth) VALUES (:name, :lastname, NOW())');
// either bind each parameter explicitly
$stmt->bindParam(':name', $name);
$stmt->bindParam(':lastname', $lastname);
$stmt->execute();
source: Datetime NOW PHP mysql (+ PDO variant)

Why does backticks fails in PDO query? [duplicate]

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

PDO query with php variables [duplicate]

This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 8 years ago.
Why this line doesn't work:
$db_Table = "myTable";
$pdo->prepare("INSERT INTO :db_Table VALUES (...
$query->execute(array(
':db_Table' => $db_Table,
Whereas this one works:
$pdo->prepare("INSERT INTO myTable VALUES (...
How can I solve it ?
Tablenames can not be replaced in a PDO Query.
Further information you can find in the following thread
Can PHP PDO Statements accept the table or column name as parameter?
unfortunately there are no builtin function for binding table names, you have to do it yourself:
$db_Table = "myTable";
$query = $pdo->prepare("INSERT INTO `$db_Table` VALUES (...)");
$query->execute();
But that is still not being escaped, one workaround is to have an array of table, then check if it exist:
$list_of_tables = array('myTable1', 'myTable2', 'myTable3');
if(!in_array($db_Table, $list_of_tables){
//table does not exist !
}

Categories