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

报告相同问题?

悬赏问题

  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格