0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

(PHP)PDOのプレースホルダーについて

Posted at

#PDOのプレースホルダーは変数名で書くべき
結論から言うとプレースホルダーには入れ込む変数名を記述するようにしましょう。
?でも可能ですしexecuteの引数の記述も減らせますが可読性や保守性面を考えると変数名で記述すべきだと言えるでしょう。

$label = '素晴らしい!!';
$n = 80;
$stmt = $pdo->prepare(
    "UPDATE
       posts 
    SET 
      message = CONCAT(?, message) 
    WHERE 
      likes >= ?"
  );
  $stmt->execute([$label, $n]);

↓書き換えると

$stmt = $pdo->prepare(
    "UPDATE
       posts 
    SET 
      message = CONCAT(:label, message) 
    WHERE 
      likes > :n"
  );
  $stmt->execute([':label' => $label, ':n' => $n]);

またexecute()の 第1引数のコロン(:)は省略できるので↓

$stmt = $pdo->prepare(
    "UPDATE
       posts 
    SET 
      message = CONCAT(:label, message) 
    WHERE 
      likes > :n"
  );
  $stmt->execute(['label' => $label, 'n' => $n]);

こうなります。
以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?