2009-09-28 74 views
2

我想知道是否準備好的語句與多個VALUES的普通mysql_query一樣。PHP MySQLi多個插入

INSERT INTO table (a,b) VALUES ('a','b'), ('c','d'); 

VS

$sql = $db->prepare('INSERT INTO table (a,b) VALUES (?, ?); 

如果我用事先準備好的聲明中循環,是MySQL的優化後臺插件像它會在第一段代碼來工作的,或只是就像每次運行一個循環內的第一段代碼一樣?

回答

10

我繼續進行測試,其中一個查詢使用準備好的語句,另一個生成整個查詢然後執行該查詢。我可能沒有做出我想知道的容易理解的東西。

這是我的測試代碼。我正在考慮準備好的語句,直到$ stmt-> close()被調用來優化它或某個東西時才停止執行。這看起來並非如此,因爲使用real_escape_string構建查詢的測試速度至少快了10倍。

<?php 

$db = new mysqli('localhost', 'user', 'pass', 'test'); 

$start = microtime(true); 
$a = 'a'; 
$b = 'b'; 

$sql = $db->prepare('INSERT INTO multi (a,b) VALUES(?, ?)'); 
$sql->bind_param('ss', $a, $b); 
for($i = 0; $i < 10000; $i++) 
{ 
    $a = chr($i % 1); 
    $b = chr($i % 2); 
    $sql->execute(); 
} 
$sql->close(); 

echo microtime(true) - $start; 

$db->close(); 

?> 
+3

我想類似的事情(多插入它會更快),因爲這個答案被標記爲正確的,這是優化的解決方案嗎?另外「因爲使用real_escape_string構建查詢的測試速度至少快10倍。」那個測試在哪裏? –

0

如果您在循環中使用準備好的語句,那麼每次運行原始查詢都會更有效率,因爲只需使用預準備語句執行一次分析即可。所以不,這個程度不一樣。

+2

但是如果你使用多行插入語法,因爲當你使用它,你就會將查詢發送到數據庫中只有一次這麼多個請求的開銷降低 – andho

0
public function insertMulti($table, $columns = array(), $records = array(), $safe = false) { 
    self::$counter++; 
    //Make sure the arrays aren't empty 
    if (empty($columns) || empty($records)) { 
     return false; 
    } 

    // If set safe to true: set records values to html real escape safe html 
    if($safe === true){ 
     $records = $this->filter($records); 
    } 

    //Count the number of fields to ensure insertion statements do not exceed the same num 
    $number_columns = count($columns); 

    //Start a counter for the rows 
    $added = 0; 

    //Start the query 
    $sql = "INSERT INTO " . $table; 

    $fields = array(); 
    //Loop through the columns for insertion preparation 
    foreach ($columns as $field) { 
     $fields[] = '`' . $field . '`'; 
    } 
    $fields = ' (' . implode(', ', $fields) . ')'; 

    //Loop through the records to insert 
    $values = array(); 
    foreach ($records as $record) { 
     //Only add a record if the values match the number of columns 
     if (count($record) == $number_columns) { 
      $values[] = '(\'' . implode('\', \'', array_values($record)) . '\')'; 
      $added++; 
     } 
    } 
    $values = implode(', ', $values); 

    $sql .= $fields . ' VALUES ' . $values; 
    //echo $sql; 
    $query = $this->dbConnection->query($sql); 

    if ($this->dbConnection->error) { 
     $this->errorLog($this->dbConnection->error, $sql); 
     return false; 
    } else { 
     return $added; 
    } 
} 

此功能適用於第一次準備多行值的一個INSERT查詢,一旦將它插入。但是,這不是一次性批量插入。