【问题标题】:Inserting using PDO bindValue in php在 php 中使用 PDO bindValue 插入
【发布时间】:2015-04-29 19:17:58
【问题描述】:

我正在尝试使用 PDO bindValue,但它对我不起作用。

 public static function insert($tableName, $columnValues = array()) {
        $columns = array_keys ( $columnValues );
        $columns = '`' . implode ( '`,`', $columns ) . '`';
        $values = null;
        $x = 1;
        $y = 1;
        foreach ( $columnValues as $value ) {
            $values .= '?';
            if ($x < count ( $columnValues )) {
                $values .= ',';
            }
            $x ++;
        }
        $sql = "INSERT INTO {$tableName} ($columns) VALUES($values)" . '</br>';
        if ($sqlString = DatabaseConnection::getConnectionInstance ()->pdo->prepare ( $sql )) {
            foreach ( $columnValues as $value ) {
                $sqlString->bindValue ( $y, $value );
                $y ++;
            }
            if ($sqlString->execute ()) {
                echo 'executed';
            }
        }

        return false;
    } 

【问题讨论】:

标签: php mysql pdo bindvalue


【解决方案1】:

我已修改您的函数以使用延迟绑定,请参阅PDO info。 注意您的implode() 不太正确。 我添加了回声以显示测试后应删除的结果。

public static function insert($tableName, $columnValues = array()) {
        $columns = array_keys( $columnValues );
        $params = array_values( $columnValues );// Array to hold values for lazy binding
        $columns = '`' . implode ("`,`",  $columns ) . '`';
        $values = null;
        $x = 1;/*
        $y = 1;*/
        foreach ( $columnValues as $value ) {
            $values .= '?';
            if ($x < count ( $columnValues )) {
                $values .= ',';
            }
            $x ++;
        }
        $sql = "INSERT INTO {$tableName} ($columns) VALUES($values)" . '</br>';
        if ($sqlString = DatabaseConnection::getConnectionInstance ()->pdo->prepare ( $sql )) {
            echo $sql;//For Testing
            echo "<br>";//For Testing
            var_dump($params);//For Testing
           if ($sqlString->execute ($params)) {
                echo 'executed';
            }
        }

        return false;
    } 

这个函数产生

INSERT INTO test (`Peter`,`Ben`,`Joe`) VALUES(?,?,?)

array(3) { [0]=> int(35) [1]=> int(37) [2]=> int(43) }  

来自

$columnValues =  array("Peter"=>35, "Ben"=>37, "Joe"=>43);
$tableName ="test";   
insert($tableName, $columnValues)   

【讨论】:

  • 我不得不更改函数以逃避 bindValue,因为没有错误也没有 +ve 结果。谢谢
  • 我的函数中没有bindValue()
  • 我尝试了函数 david strachan 但没有 +ve 结果
  • echo $sql& var_dump($params) 的结果
  • $sql 是 INSERT INTO users (username,password) VALUES(?,?) 和 var_damp 是数组 (size=2) 0 => int 23456789 1 => int 234567跨度>
猜你喜欢
  • 1970-01-01
  • 2016-09-11
  • 2014-01-26
  • 2013-01-03
  • 2011-02-11
  • 2013-11-12
  • 2012-07-31
  • 2016-10-12
相关资源
最近更新 更多