如何最好地完成这项任务?
require_once('models/databaseModel.class.php');
class crudModel extends databaseModel{
public function __construct(){
parent::__construct();
}
public static function create(&$data, $tbl){
// TEST $data array
// $data = array('name'=>'philip','email'=>'me@myemail.com','age'=>28);
//This is how I would like $value1
// ":$name', ':$age', ':$email' ";
//This is how I would like $value2
// "ssi";
//MY TEST
$params = array();
$results = array();
foreach($data as $k => $v){
if(is_string($v)){
$params = 's';
}
if(is_int($v)){
$params = 'i';
}
$results = array_fill(0, count($v), $params);
if(is_array($results)){
$value2 = implode('', $results);
}
}
$sql = "INSERT INTO $tbl('".implode(',', array_keys($data))."')VALUES('".$value1."')";
$stmt = $link->prepare($sql);
$stmt->bind_params($value2, $value1);
$stmt->execute();
}
}
答案 0 :(得分:0)
尝试类似
的内容$columns = implode(',', array_keys($data));
$values = array_values($data);
$placeHolders = trim(str_repeat('?,', count($values)), ',');
$sql = "INSERT INTO {$tbl}({$columns}) VALUES({$placeHolders})";
$stmt = $link->prepare($sql);
$stmt->execute($values);
// FETCH DATA...