【问题标题】:Update two columns in pdo更新 pdo 中的两列
【发布时间】:2014-04-03 05:51:32
【问题描述】:

我有这个功能(更新)用 pdo 更新 mysql 表中的数据
使用此功能更新一列时,它工作正常。
但是当使用它更新多个列时,此函数会将最后一个值添加到所有列
您可以查看照片中的问题
http://postimg.org/image/z1kv5jh9j/
把我用的代码搞砸了
请帮忙

<?php
public function query($sql, $fields = array()){

        if($this->_query = $this->_pdo->prepare($sql)){
            $i = 1;
            if($i <= count($fields)){
                foreach ($fields as $param){
                    $this->_query->bindParam($i, $param);
                    $i++;
                }
            }
            //die($sql);
            if($this->_query->execute()){
                return $this->_query;
            }

        }

    }

    public function Update($tbl_name, $fields = array(),$id){
        $set = '';
        $x = 1;
        $bindvalues = array_values($fields);
        foreach ($fields as $columns => $values) {
            $set .= "`{$columns}` =?";
            if ($x < count($fields)){
                $set .= ", ";
            }
            $x++;
        }

        $id = intval($id);
        $sql = "UPDATE `{$tbl_name}` SET {$set} WHERE `id`={$id} ";
        //die($sql);
        if($this->query($sql,$fields) == true){
            echo "Data updated Successfully";
        }
    }
?>

【问题讨论】:

  • 查询中的参数是否使用了“:”?通常,查询看起来像“更新表 SET VALUES param=:param ...”也许这就是问题所在?
  • @ms88-aut 他正在使用未命名的参数。 $set .= "`{$columns}` =?"

标签: php mysql pdo


【解决方案1】:

您需要使用bindValue() 而不是bindParam(),因为bindParam() 通过引用传递给PDO。这使它始终使用$param 变量中设置的最后一个值。

public function query($sql, $fields = array()){

        if($this->_query = $this->_pdo->prepare($sql)){
            $i = 1;
            if($i <= count($fields)){
                foreach ($fields as $param){
                    $this->_query->bindValue($i, $param);
                    $i++;
                }
            }
            //die($sql);
            if($this->_query->execute()){
                return $this->_query;
            }

        }

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-18
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2018-05-12
    • 2013-02-25
    • 1970-01-01
    相关资源
    最近更新 更多