Php 从多维空间插入值。使用PDO的阵列需要很长时间。有更好的办法吗?
我得到了650行的数组。在本地计算机上使用PDO插入此文件需要10-15秒。 那太慢了。这是因为磁盘读/写吗?或者是别的什么 这是我的数组(前4行): 这是我的代码:Php 从多维空间插入值。使用PDO的阵列需要很长时间。有更好的办法吗?,php,mysql,database,pdo,Php,Mysql,Database,Pdo,我得到了650行的数组。在本地计算机上使用PDO插入此文件需要10-15秒。 那太慢了。这是因为磁盘读/写吗?或者是别的什么 这是我的数组(前4行): 这是我的代码: $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
$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]));
}
解决方案
对于那些想知道的人,她的eis是我插入多行的解决方案仅使用一个
$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);
}
原因可能是,速度慢可能因许多因素而异
考虑使用一个查询来插入多个记录< /p>您使用的是什么数据库引擎(myiSAM,INNODB…?)我使用InnobDB.then,您可能需要考虑在您的开发机器上的MySQL配置中设置“代码> NojdBulfSuxLogyAt*TrxOffice=2 < /Calp>和<代码> SycCyBiLoSQL=0 < /Cord>。这将最大限度地减少磁盘刷新,并可通过多种因素提高应用程序的速度。谢谢。这让我走上了正确的道路。其实我早就试过了,但没有成功。但现在我找到了解决办法。见上文。
$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);
}