这是我在 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"));