带数组的PHP PDO插入
我在使用PDO将数据插入数据库时遇到问题,因为输入的结果错误 这个班的工作如下:带数组的PHP PDO插入,php,sql,arrays,pdo,Php,Sql,Arrays,Pdo,我在使用PDO将数据插入数据库时遇到问题,因为输入的结果错误 这个班的工作如下: class PDOMySql{ public function connect(){ try{ $dbh = new PDO('mysql:host='.$this->server.';dbname='.$this->database,$this->username,$this->password); $
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:第二栏。
c:第二栏。
d:asdfasd
正如您所看到的,第二个值不是输入null,而是输入到c列中
是否有一种更简单的方法来插入动态创建的值,因为有些值可能为null,而使用上面的方法似乎会忽略null并使用最后一个值。有人知道为什么会发生这种情况,或者是否有更简单的方法可以做到这一点吗?我建议使用bindValue()而不是bindParam()
但是,有这么多匿名值
(?,?,?,?)
,这被认为是不好的做法。。。您应该使用占位符,如果它们来自$\u POST数组,您可以使用$\u POST数组并将键用作占位符这听起来像个bug。如果您的PHP和PDO版本存在已知问题,请与PHP bugtracker联系。如果您没有传递null
,而是传递字符串'null'
。尝试了它并编辑了它以添加它,但有人编辑了它并删除了editI已更改代码使用带键的数组并将我的foreach更改为foreach($value as$key=>$item)然后使用bindValue(“:”.$key.,$item,PDO::PARAM_STR);
$prepare->bindValue($i, $item, $param);