douwen7331
2018-07-04 02:22
浏览 62
已采纳

冒号意味着什么:使用php bindParam时的名字

The PHP manual has this example for the PDO bindParam statement:

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>

Does the : colon just mean that :colour is a parameter?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doushanmo7024 2018-07-04 02:35
    已采纳

    That maps to the named placeholder in the query. It is not required for the binding, the driver will auto-added it if not present.

    In your code you have

    $sth = $dbh->prepare('SELECT name, colour, calories
        FROM fruit
        WHERE calories < :calories AND colour = :colour');
                         ^^^^^^^^^              ^^^^^^^
    

    The driver reads anything with the : and trailing text as a placeholder. It then swaps that content with the value being bound, escapes all special characters, and quotes the string.

    So then your bindparam has

    :calories and :colour which match up to each of those. Let's say $calories had o'brien. When the query went to the DB it would be:

    SELECT name, colour, calories
    FROM fruit
    WHERE calories < 'o\'brien'
    

    PDO also supports unnamed placeholders which are just question marks ?. You bind these by position.

    $sth = $dbh->prepare('SELECT name, colour, calories
            FROM fruit
            WHERE calories < ? AND colour = ?');
    

    and then use a 1 because it is the first placeholder.

    $sth->bindParam(1, $calories, PDO::PARAM_INT);
    

    Additionally you can just pass all values to the execute function as an array and it will do the binding as well.

    Regardless of bindparam or execute binding you have to address the binding by how you use it in the query. Unnamed is positional, named is by name.

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题