Ogum
Ogum

Reputation: 379

Update old Mysql statement with PDO

How can i update this old statement into the PDO statement?

The old one:

$query = "UPDATE  tbl_product
          SET
         image = CASE WHEN '$post_image' IS NULL OR CHAR_LENGTH('$post_image') = 0 THEN image ELSE '$post_image' END

and the new one PDO

$query = "UPDATE tbl_product 
                SET 
                image=:image 

Thanks!

Upvotes: 0

Views: 66

Answers (1)

Qirel
Qirel

Reputation: 26450

PDO has the advantage of named placeholders. Unlike MySQLi, which only has ? as a placeholder (PDO has this too), you can use :image as a placeholder, and repeat it where necessary - PDO will then substitute the placeholders for the value that is bound to that placeholder, either in execute() or by using bindParam()/bindValue().

Simply replace all instances of '$post_image' to :image. Note that there are no quotes around the placeholder.

$query = "UPDATE  tbl_product
          SET image = CASE WHEN :image IS NULL OR CHAR_LENGTH(:image) = 0 THEN image 
                           ELSE :image END";

Then you'd prepare and execute the query, assigning the $post_image value to the :image placeholder. Note how that is inside an array [..].

$stmt = $pdo->prepare($query);
$stmt->execute(["image" => $post_image]);

Documentation:

Upvotes: 2

Related Questions