2015-06-16 56 views
0

我正在嘗試構建一個通用函數來插入。我的目標是傳遞表格,列,值和類型以填充插入。在準備聲明中綁定可變數量的參數

我唯一的問題是語句:

$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語句看起來很好。另外,類型準備 - 我只需要動態綁定參數的方式...

+0

你不能。 'bindparam'是1:1映射。您可以使用execute()中的數組選項一次傳入所有內容。 '$ stmt-> execute(array(':foo'=>'bar',....));' –

+0

你能給我更多的信息嗎?這樣做是否有消極的一面? –

+0

好吧,這隻有幫助執行查詢。如果你想要綁定結果值,你會遇到很多bindparam()調用。 –

回答

1

嗯,我認爲,在$列定義爲$columns = array('col1', 'col2'/*...*/);$值$values = array($val1, $val2/*...*/);

我會爲列名轉義創建函數。

$escapeCols = function($column) { return sprintf('%s的', $column); };

創建另一個功能?佔位符

$placeholders = function ($values) { return array_fill(0, count($values), '?'); }

可以比準備查詢

$sql = sprintf( 'INSERT INTO %s (%s) VALUES (%s)', $table, implode(', ', array_map($escapeCols, $columns), implode(', ', $placeholders($values)) );

然後你就可以調用execute

$stmt = $connection->prepare($sql); $stmt->execute($values);

這種方式可以很容易地轉化,如果你將有$值定義爲

$values = array('col1' => $va1, 'col2' => $val2);

+0

首先謝謝 - 我試過這個,但收到以下錯誤:警告:mysqli_stmt :: execute()期望完全0參數,1給出/var/www/virtual/.../helper.php在線126 –

+0

哦對不起,我錯過了你正在使用* mysqli *。我的評論可以在* pdo *上使用。其中有更好的能力。 – venca

相關問題