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

冒号意味着什么:使用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条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效