我有一张带汽车的桌子。每辆车都有一个或多个调整阶段,位于另一张桌子上。
在带有调整阶段的表中;有一个汽车标识符:[cId] = car id。
首先,我复制汽车并将新生成的 id 存储mysql_insert_id()
到$new_carId
.
然后,我根据汽车标识符 [cId] 获取所有相关的调整阶段,并执行与汽车相同的操作,但在循环中while()
。
现在,新的复制阶段具有旧车的 [cId]。
我现在需要用存储的任何 id 替换 [cId],$new_carId
以便将重复的阶段分配给新车。
我的看法;我有两个选择:
要么直接在INSERT
-query中发生,要么在-loop结束时
执行 sql 。UPDATE
while()
到目前为止,这是我的代码:
/**
* Duplicate an existing car with associated tuning stage:
* Each car may have more than one associated tuning stage located in a separate table.
* We need to make sure all stages is duplicated as well, and assigned to the new car.
*
* [cId] car id.
*
* debug() is a personal debugging function.
*/
if (isset($_POST['duplicate_car'])){
# duplicate the car.
$orgCar_id = (int)mysql_real_escape_string($_POST['orgCar_id']); // ID of the car we make the duplicate from.
$sql_car = 'INSERT INTO TUNE_cars (make, model, chassis, motor, motorkode, orgEff, orgNm, year, options, note)
SELECT make, model, chassis, motor, motorkode, orgEff, orgNm, year, options, note FROM TUNE_cars WHERE cId = '.$orgCar_id;
// debug($sql_car);
$qry_car = mysql_query($sql_car);
$new_carId = (int)mysql_real_escape_string(mysql_insert_id()); // We need to attach this ID to the new duplicated tuning stages.
//
/**
* Duplicate any associated tuning stages:
* We need to fetch all stages associated with the old car,
* duplicate them aswell, and attach them to the new car.
*
* [sId] stage id
* [cId] car id. This connects the stages to a given car.
*/
# fetch all stages associated with the old car.
$sql_stages = 'SELECT sId FROM TUNE_stages WHERE cId = '.$orgCar_id;
// debug($sql_stages);
$qry_stages = mysql_query($sql_stages);
//
# duplicate the stages.
while($get_stage = mysql_fetch_assoc($qry_stages)){
$sql_dup_stage = 'INSERT INTO TUNE_stages (cId, stage, stageHp, stageNm, stagePrice, stageMethod, stageDyno, sinfo, snote)
SELECT '.$new_carId.', stage, stageHp, stageNm, stagePrice, stageMethod, stageDyno, sinfo, snote FROM TUNE_stages WHERE sId = '.$get_stage['sId'];
// debug($sql_dup_stage);
$qry_dup_stage = mysql_query($sql_dup_stage);
//
}
//
/**/
}
/**/
如你看到的; 我使用了最后一种方法:
我在循环UPDATE
结束时做了一个while()
。
我确实相信这可以做得更简单,并愿意接受建议......