这是我的PDO插入方法,它工作100%。 这种“插入”方法接受表,列和价值,但我想让它的通用性。 (我想有或没有列名插入值)
public function insert($table, $pair = array()){
try{
$Sql = "INSERT INTO $table ( ";
$Sql .= implode(", ", array_keys($pair));
$Sql .= " )";
$Sql .= " VALUES (";
$Sql .= implode(", ", array_fill("0", count($pair), " ?"));
$Sql .= " )";
$array = array_combine(array_keys(array_fill("1", count($pair), ":")), $pair);
$ready = $this->conn->prepare($Sql);
foreach($array as $key => $value)
{
$ready->bindValue($key, $value, PDO::PARAM_STR);
}
$ready->execute();
}
catch(Exception $e){
$this->trace .= " • ". $e->getMessage();
}
}
$new = new community();
echo $new->insert("table", array("Col1" => "value1", "col1" => "value1"));