我最近不得不做类似的事情,所以我想我发布了适用于任何尺寸表的解决方案,包括示例。它只需要一个配置数组,可以调整到几乎任何大小的表。
$copy_table_row = array(
'table'=>'purchase_orders', //table name
'primary'=>'purchaseOrderID', //primary key (or whatever column you're lookin up with index)
'index'=>4084, //primary key index number
'fields' => array(
'siteID', //copy colunm
['supplierID'=>21], //overwrite this column to arbirary value by wrapping it in an array
'status', //copy colunm
['notes'=>'copied'], //changes to "copied"
'dateCreated', //copy colunm
'approved', //copy colunm
),
);
echo copy_table_row($copy_table_row);
function copy_table_row($cfg){
$d=[];
foreach($cfg['fields'] as $i => $f){
if(is_array($f)){
$d['insert'][$i] = "`".current(array_keys($f))."`";
$d['select'][$i] = "'".current($f)."'";
}else{
$d['insert'][$i] = "`".$f."`";
$d['select'][$i] = "`".$f."`";
}
}
$sql = "INSERT INTO `".$cfg['table']."` (".implode(', ',$d['insert']).")
SELECT ".implode(',',$d['select'])."
FROM `".$cfg['table']."`
WHERE `".$cfg['primary']."` = '".$cfg['index']."';";
return $sql;
}
这将输出如下内容:
INSERT INTO `purchase_orders` (`siteID`, `supplierID`, `status`, `notes`, `dateCreated`, `approved`)
SELECT `siteID`,'21',`status`,'copied',`dateCreated`,`approved`
FROM `purchase_orders`
WHERE `purchaseOrderID` = '4084';