繁体   English   中英

如何循环 PHP 的 PDO 绑定参数

[英]HOW TO LOOP PHP'S PDO BIND PARAM

我现在正在创建我自己的查询构建器,并且我坚持使用 PDO 的准备好的语句。 是否可以循环 PDO 的 BindParam。 我是使用 foreach() 做到的,但它不仅仅适用于循环执行的最后一个数据。

$sql = "SELECT * FROM users WHERE id = :a OR fname = :b";

$array = array(":a"=>"10002345", "Josh");
$stmt = $conn->prepare($sql); 

foreach($array as $key => $value ) {
    $stmt->bindParam($key, $value);
}

$stmt->execute();

它只绑定循环执行的最后一个数据。

使用更好? 查询中的占位符并传递要execute的数据数组:

$sql = "SELECT * FROM users WHERE id = ? OR fname = ?";
$array = array("10002345", "Josh"); // you don't even need keys here
$stmt = $conn->prepare($sql); 
$stmt->execute($array);

只是偶然发现了这一点,但仅供将来参考......

首先,我将假设您的示例应该读取$array = array(":a"=>"10002345", ":b"=>"Josh"); ,因为即使您的:b密钥不存在也会出现问题。


在这一点:

foreach($array as $key => $value ) {
    $stmt->bindParam($key, $value);
}

您还没有“通过引用传递”。 $value应该修改为&$value

foreach($array as $key => &$value ) {
    $stmt->bindParam($key, $value);
}

这是因为bindParam方法签名要求该值是变量引用:

public function bindParam ($parameter, &$variable, $data_type = PDO::PARAM_STR, $length = null, $driver_options = null) {}

(注意$variable之前的& )。


原始查询 (sans & ) 的最终结果是所有:params都将设置为原始循环中$value的最后一次迭代中的$value

所以,结果

$sql = "SELECT * FROM users WHERE id = :a OR fname = :b";

$array = array(":a"=>"10002345", ":b"=>"Josh");

$stmt = $conn->prepare($sql); 

foreach($array as $key => $value ) {
    $stmt->bindParam($key, $value);
}

$stmt->execute();

将是SELECT * FROM users WHERE id = 'Josh' OR fname = 'Josh'


使用命名参数 ( :param ) 比位置参数 ( ? ) 更有优势,因此值得为准备好的语句保留该选项,而不是“最好使用?占位符”的公认答案,事实并非如此。

在我的数据库抽象层中,我使用以下实用程序函数:

/**
 * getFieldList return the list with or without PK column
 * @param bool $withID - true when including parameter
 */
static protected function getFieldList( $withID = false )
{
    if( $withID )
        $result = '`' . static::getTableName( ) . '`' .
            '.`' . static::getPrimaryKeyName( ) . '`, ';
    else
        $result = '';

    return $result .= '`' . static::getTableName( ) . '`.' . 
        '`' . implode( '`, `'.static::getTableName( ) . '`.`', static::getFieldNames( ) ) . '`';
}

/**
 * getFieldPlaceholders - 
 * @return string - all PDO place holders prefixed :
 */
static protected function getFieldPlacholders( )
{
    return ':' . implode( ',:', static::getFieldNames( ) );
}

/**
 * getUpdateList - SQL updates section
 * @return string
 */
static private function getUpdateList( )
{
    $result = array( );
    foreach( static::getFieldNames( ) as $field ) {
        if( $field === static::getPrimaryKeyName() ) continue;
        $result[] = '`' . $field . '`=:' . $field;
    }
    return implode( ',', $result );
}

/**
 * Bind the fields to PDO placeholdes
 * @param PDOStatement $stmt statement that the fields are bound to
 * @return void
 */
protected function bindFields( $stmt )
{
    foreach( array_keys($this->fields) as $field ) {
        if( $field === static::getPrimaryKeyName() ) continue;
        $stmt->bindParam( ':' . $field, $this->fields[$field] );

        // echo $field . '->' . $this->fields[$field] . '<br>';
    }
}
/**
 * Bind the fields to the placeholders
 * @param PDOStatement $stmt - that the fields are bind to
 * @return void
 */
protected function bindColumns( $stmt, $withID = false )
{
    if( $withID )
        $stmt->bindColumn( static::getPrimaryKeyName(), $this->ID );
    foreach( static::getFieldNames() as $fieldname )
    {
        $stmt->bindColumn( $fieldname, $this->fields[$fieldname] );
    }   
}

/**
 * parseResultset
 * Set the values of the select results, resets dirty (object is in sync)
 * @param mixed[] $result - associative array
 */
protected function parseResultset( $result )
{
    foreach( $result as $field=> $value ) {
        if( $field === static::getPrimaryKeyName() )
            $this->ID = $value;
        $this->fields[$field] = $value;
    }
    $this->dirty = array();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM