【问题标题】:What does the colon mean in :name when using php bindParam使用php bindParam时:name中的冒号是什么意思
【发布时间】:2018-12-12 09:08:14
【问题描述】:

PHP 手册中有这个 PDO bindParam 语句的示例:

<?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();
?>

: 冒号只是表示:colour 是一个参数吗?

【问题讨论】:

    标签: php pdo


    【解决方案1】:

    映射到查询中的命名占位符。绑定不需要,如果不存在,驱动程序会自动添加。

    在你的代码中

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

    驱动程序读取带有: 和尾随文本作为占位符的任何内容。然后,它将该内容与绑定的值交换,转义所有特殊字符,并引用字符串。

    那么你的bindparam

    :calories:colour 与这些匹配。假设$calorieso'brien。当查询进入数据库时​​,它将是:

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

    PDO 还支持未命名的占位符,它们只是问号?。您可以按位置绑定它们。

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

    然后使用1,因为它是第一个占位符。

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

    此外,您可以将所有值作为数组传递给execute 函数,它也会执行绑定。

    无论bindparamexecute 绑定,您都必须通过在查询中使用绑定来解决绑定问题。未命名是位置,命名是按名称。

    【讨论】:

    • 抱歉,这个答案超出了我的想象。例如colour 是命名占位符吗?对colour(带和不带冒号)的两个引用是指同一个对象吗?
    • 我的示例实际上没有意义,因为 &lt; 的字符串不是最好的,但希望能证明它是如何工作的。
    【解决方案2】:

    参数

    参数标识符。对于使用命名占位符的准备好的语句,这将是一个形式为 :name 的参数名称。对于使用问号占位符的预处理语句,这将是参数的 1 索引位置。

    变量

    要绑定到 SQL 语句参数的 PHP 变量的名称。

    请参阅此处的文档以获取参考 http://php.net/manual/en/pdostatement.bindparam.php

    $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) 
    VALUES (:firstname, :lastname, :email)");
    $stmt->bindParam(':firstname', $firstname);
    $stmt->bindParam(':lastname', $lastname);
    $stmt->bindParam(':email', $email);
    
    // insert a row
    $firstname = "John";
    $lastname = "Doe";
    $email = "john@example.com";
    $stmt->execute();
    

    【讨论】:

      猜你喜欢
      • 2011-02-23
      • 2012-10-09
      • 2020-05-21
      • 1970-01-01
      • 2019-09-14
      • 2012-09-25
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多