在我的网页中,有一个 CSV 导入部分。用户可以导入数千条记录。我需要将 csv 详细信息插入到 2 个表中。
第一个表包含基本信息。第二个包含其他附加信息。所以我需要将第一个表的插入 ID 保存到第二个表中。
针对上述需求,我写了2条mysql语句。但导入需要更多时间。这里,是否可以使用单个查询将记录插入到 2 个表中?
请指教。
最佳答案
您不能同时插入两个表(因为您需要第一个表中的 id),但您可以为第一个表逐一插入,为第二个表插入一个单个查询,如下所示:
$main_data = array('data1', 'data2', 'data3');
$new_data = array();
foreach($main_data as $data) {
mysql_query("insert into table1 (data) values ('$data')");
$new_id = mysql_insert_id();
// Save the new id into an array + the data
$new_data[$new_id] = $main;
}
$insert_into = array();
// Create a new insert statement
foreach($new_data as $new_key => $data) {
$insert_into[] . "($new_key, '$data')"
}
$imploded_data = implode(',', $insert_into);
if (count($insert_into) > 0) {
// The result will be something like Insert into `table2` (id, value) values (1, 'data1'), (2, 'data2'),(3, 'data3');
mysql_query("insert into `table2` (id, value) values $imploded_data");
}
关于php - 一次向两个表中插入记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19315976/