phpcms复制表中的一条记录并插入的实现代码

发布时间:2020-10-06编辑:脚本学堂
有一个变态的需求,导出一个文章表,插入到 PHPCMS 中的内容表 phpcms_content 去,实现文章可以发布到不同的栏目中。即需要复制一条记录,并修改其 catid,再插入到表尾的位置上。

mysql 复制一条数据并插入的语句:

INSERT INTO phpcms_content (SELECT ".$r[$i]['aid']." + 520, ".$r[$i]['cateid'].", news_catid, catid, typeid, areaid, title, style, thumb, keywords, keywords, posids, url, listorder, status, userid, username, inputtime, updatetime, searchid, islink, prefix FROM phpcms_content WHERE contentid = '".$r[$i-1]['aid']."')

大致为:insert into a SELECT id+1, ...(其它字段) FROM a ;

程序代码如下。

<?php
$query  = "SELECT * FROM articleincategory ORDER BY ArticleID  ";
$result = $connector -> query($query);

$i = 0;
while($myrow = $connector -> fetch_array($result))
{
 $r[$i]['aid'] = $myrow["ArticleID"];
 $r[$i]['cateid'] = $myrow["CategoryID"];
 $i++;
}

for($i = 0; $i < count($r); $i++)
{
if($i > 0)
 {
  if( $r[$i]['aid'] == $r[$i-1]['aid'] )
  {
   echo '第 '. $i. ' 条数据 '. $r[$i]['aid'] .' 与前一条数据 '. $r[$i-1]['aid'] .' 重复'.'<br/>';
   $sql = " INSERT INTO phpcms_content (SELECT ".$r[$i]['aid']." + 520, ".$r[$i]['cateid'].", news_catid, catid, typeid, areaid, title, style, thumb, keywords, keywords, posids, url, listorder, status, userid, username, inputtime, updatetime, searchid, islink, prefix FROM phpcms_content WHERE contentid = '".$r[$i-1]['aid']."') ";
   //$sql = " INSERT INTO phpcms_c_news (SELECT ".$r[$i]['aid']." + 520, template, titleintact, content, groupids_view, readpoint, author, copyfrom, paginationtype, maxcharperpage, sub_title FROM phpcms_c_news WHERE contentid = '".$r[$i-1]['aid']."')  ";
   echo $sql.'<br />';
   //$result = $connector -> query($sql);
   //INSERT INTO test (SELECT id + 10, name, class, score FROM test WHERE id = '1');
  }
  
  else if( $r[$i]['aid'] != $r[$i-1]['aid'] )
  {
   $sql = " UPDATE phpcms_content SET origin_cateid = '".$r[$i]['cateid']."' WHERE contentid = '".$r[$i]['aid']."'  ";
   echo $sql.'<br />';
   //$result = $connector -> query($sql);
  }  
 }
}
?>

不需要插入的话更简单:

insert into mytable (select * from mytable where id=1) ON DUPLICATE KEY UPDATE id=2;
--或
update mytable set id=2 where id=1;