我正在嘗試構建一個通用函數來插入。我的目標是傳遞表格,列,值和類型以填充插入。在準備聲明中綁定可變數量的參數
我唯一的問題是語句:
$stmt -> bind_param($types, $var1, $var2 ...);
什麼,我基本上會需要的是這樣的:
$stmt -> bind_param($types, $array);
這是我得到至今:
function insert($into, $columns, $values, $types) {
global $connection;
// Check Correct Length
if(count($columns) != count($values) ||
count($columns) != count($types)) {
return false;
}
$count = count($columns);
$column_string = "";
$value_string = "";
$value_types = "";
for($i = 0; $i < $count; $i++) {
$column_string .= $columns[$i];
$value_types .= $types[$i];
$value_string .= '?';
if($i + 1 < $count) {
$column_string .= ',';
$value_string .= ',';
}
}
$sql = "INSERT INTO $into ($column_string) VALUES ($value_string)";
// Execute Statement
if($stmt = $connection -> prepare($sql)) {
// $stmt -> bind_param("sss", $transaction, $email, $status);
// What to do here?
$stmt -> execute();
$stmt -> close();
}
SQL語句看起來很好。另外,類型準備 - 我只需要動態綁定參數的方式...
你不能。 'bindparam'是1:1映射。您可以使用execute()中的數組選項一次傳入所有內容。 '$ stmt-> execute(array(':foo'=>'bar',....));' –
你能給我更多的信息嗎?這樣做是否有消極的一面? –
好吧,這隻有幫助執行查詢。如果你想要綁定結果值,你會遇到很多bindparam()調用。 –