2011-04-11 9 views
5

Obtuve una matriz de 650 filas. Insertar esto usando PDO toma entre 10 y 15 segundos en mi computadora local. Eso es muy lento. ¿Esto se debe a la lectura/escritura de disco? O podría ser algo más?Insertar valores de multidim. Array usando PDO toma mucho tiempo. ¿Hay una mejor manera?

Esta es mi array (4 primeras filas):

Array 
(
[0] => Array 
    (
     [0] => 3 
     [1] => 1 
    ) 

[1] => Array 
    (
     [0] => 3 
     [1] => 2 
    ) 

[2] => Array 
    (
     [0] => 3 
     [1] => 5 
    ) 

[3] => Array 
    (
     [0] => 8 
     [1] => 1 
    ) 
) 

y este es mi código:

$stmt = $this->db->prepare("INSERT INTO sl_link_store_category (item_a_ID, item_b_ID) VALUES (:item_a_ID, :item_b_ID)"); 

foreach($my_array as $row) { 
    $stmt->execute(array(':item_a_ID' => $row[0], ':item_b_ID' => $row[1])); 
} 

SOLUCIÓN

Para aquellos que se pregunta, sus eis mi solución para insertar múltiples filas
usando solo una $stmt->execute:

$input_arr; // This array one has lots of values 

    $sql = "INSERT INTO sl_link_store_category (field_a, field_b) VALUES "; 

    $i = 0; 
    // I create the query string with unique prepared values 
    // I could probably have used a for loop since I'm not using any 
    // values from $row 
    foreach($input_arr as $row) { 
     $i++; 
     $sql .= "(:field_a_$i, :field_a_$i), "; 
    } 

    // Remove the last comma (and white space at the end) 
    $sql = substr(trim($sql), 0, -1); 

    $stmt = $this->db->prepare($sql); 

    // I need to create a new associative array with field name 
    // matching the prepared values in the SQL statement. 
    $i = 0; 
    $arr = array(); 

    foreach($input_arr as $row) { 
     $i++; 
     $arr[":field_a_$i"] = $row[0]; 
     $arr[":field_b_$i"] = $row[1]; 
    } 

    $stmt->execute($arr); 
    } 
+0

¿Qué motor de base de datos (MyISAM, InnoDB ...) está usando? – Matthew

+0

@konforce - Estoy usando InnobDB. – Steven

+0

, es posible que desee considerar establecer 'innodb_flush_log_at_trx_commit = 2' y' sync_binlog = 0' en la configuración de MySQL en su máquina de desarrollo. Esto minimizará el enjuague del disco y puede acelerar su aplicación por muchos factores. – Matthew

Respuesta

3

La razón por la que puede ser tan lento puede variar en función de muchos factores.

considerar el uso de una consulta para insertar varios registros PDO Prepared Inserts multiple rows in single query

+0

Gracias. Me puso en el camino correcto. De hecho, lo intenté antes, pero no funcionó. Pero ahora encontré la solución. Véase más arriba. – Steven

Cuestiones relacionadas