-1

我在使用 PDO 将数据插入数据库时​​遇到问题,因为输入了错误的结果。

该课程的工作方式如下:

class PDOMySql{
public function connect(){
            try{
                $dbh = new PDO('mysql:host='.$this->server.';dbname='.$this->database,$this->username,$this->password);
                $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
                if(!$dbh){
                    throw new Exception('Error Connecting to Server');
                }
                return $dbh;

            }   catch(Exception $e){
                    if(MAILING == "ON"){
                        $this->report->mailing($e);
                    }
                    else{
                        throw $e;
                    }
            }
        }

public function insert($query,$values,$dbh){
        try{
            if(!is_array($values)){
                throw new Exception("Values must be in array format: e.g: array('a','b','c')");
            }
            $a = substr_count($query,'?');
            $b = count($values);
            if($a != $b){
                throw new Exception("Number of values must match the number of placements");
            }
            $prepare = $dbh->prepare($query);
            $i = 1;
            foreach($values as $item){
                $type = strtolower(gettype($item));
                if($type == "null"){
                    $param = PDO::PARAM_NULL;
                }
                elseif($type == "string"){
                    $param = PDO::PARAM_STR;
                }
                elseif($type == "integer"){
                    $param = PDO::PARAM_INT;
                }
                else{
                    throw new Exception("Type: PDO::PARAM_".$type. " Not currently supported");
                }
                    $prepare->bindParam($i, $item, $param);
                $i++;
            }

            $prepare->execute();
            $lastId = $dbh->lastInsertId();             
            return $lastId;

        }   catch(Exception $e){
            throw $e;
        }

    }

}

当类被这样调用时:

$db = new MySql(); $con = $db->connect();
$sql = "INSERT INTO users (a,b,c,d) VALUES (?,?,?,?)";
$values = array("1st column", "2nd column",null,"asdfasd");
$a = $db->insert($sql,$values,$con);

插入的值如下: a :第一列。b:第 2 列。c:第 2 列。d:asdfasd。

如您所见,第二个值不是输入 null,而是放入 c 列。

有没有更简单的方法来插入动态创建的值,因为有些可能是 null 并且使用上面的这个方法似乎忽略了 null 并使用最后一个值。有谁知道为什么会发生这种情况,或者是否有更简单的方法?

4

1 回答 1

0

我建议使用 bindValue() 而不是 bindParam()。

http://php.net/manual/en/pdostatement.bindvalue.php

$prepare->bindValue($i, $item, $param);

但是,拥有这么多匿名值被认为是不好的做法(?,?,?,?)......您应该使用占位符,如果它们来自 $_POST 数组,您可以 foreach $_POST 数组并将键用作占位符

于 2013-06-25T14:19:18.910 回答