只要您的值是一个数组,您就可以使用随机数量的值执行准备好的语句。示例(未经测试):
public function insert($table, $rows, $values) {
$params = rtrim(", ", str_repeat("?, ", count($values)));
try {
$stmt = $this->DBH->prepare("INSERT INTO $table ($rows) VALUES ($params)");
for($i = 1; $i <= count($values); $i++) {
$stmt->bindValue($i, $values[$i-1]);
}
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo "Oops... {$e->getMessage()}";
}
}
编辑仅传递两个参数($table
并$data
作为关联数组),您可以执行以下操作(未经测试):
public function insert($table, $data) {
$keys = array_keys($data);
$values = array_values($data);
$params = rtrim(", ", str_repeat("?, ", count($values)));
try {
$stmt = $this->DBH->prepare("INSERT INTO $table (`".implode("`,`", $keys)."`) VALUES ($params)");
$stmt->execute($values);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo "Oops... {$e->getMessage()}";
}
}