我有一个班级,在那个班级里,我有一个方法 像这样:
public function insert($fields){
//$fields is the array containing key and values like this
// $fields['name'=>'name_field','city'=>'city_field'];
//INSERT INTO table_name (name,city) VALUES (':name',':city')
$sql = "";
$sql .= "INSERT INTO table_name (".implode(',', array_keys($fields)).") VALUES ";
$sql .= "(':".implode("',':", array_keys($fields)).")";
$stmt = $this->connect()->prepare($sql);
//so here how can I bind parameters??
$stmtExec = $stmt->execute();
}
答案 0 :(得分:0)
就像我在上面的评论中所说,您应该使用foreach
循环来遍历您的fields
数组,然后bindValue
。
这应该有效:
$fields = ['name'=>'name_field','city'=>'city_field'];
$implodeValue = implode(', ', array_keys($fields));
$implodeValuePlaceholder = implode(", :", array_keys($fields));
$sql = "INSERT INTO table_name ($implodeValue) VALUES (:".$implodeValuePlaceholder.")";
$stmt = $this->connect()->prepare($sql);
foreach ($fields as $key => $value) {
echo $stmt->bindValue(':'.$key, $value);
}
$sql->execute();
现在这应该有效。