更新pdo中的两列

时间:2014-04-02 20:14:50

标签: php mysql pdo

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

<?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";
        }
    }
?>

1 个答案:

答案 0 :(得分:1)

您需要使用bindValue()代替bindParam(),因为bindParam()会传递给PDO byref。这使得它始终使用$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;
            }

        }

    }