我在使用 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 并使用最后一个值。有谁知道为什么会发生这种情况,或者是否有更简单的方法?