php - 更新 pdo 中的两列

标签 php mysql pdo

我有这个函数(更新)来使用 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";
        }
    }
?>

最佳答案

您需要使用 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;
            }

        }

    }

关于php - 更新 pdo 中的两列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22822067/

相关文章:

php - 用 Woocommerce 3 中的自定义文本替换产品零显示价格

php - Vagrant 与 Chef : How to install a newer version of PHP?

mysql - Rails 4 连接关联表 - 当某些记录没有关联时进行排序

php - 使用 PDO fetch 获取数组并使用 if 语句

php - PDO : Uncaught PDOException: could not find driver

php - 日期时间输入字段的值无法通过验证

php - 我怎样才能编写这段代码来实现相同的结果,但只使用一个 foreach 语句?

php - MySQL SUBSTR() 函数

php - Json 获取队列

php - PDO:绑定(bind)时使用 data_type 的目的是什么?