微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 在MySQL中复制一条记录

我有一个表,我想复制表中的特定行.我知道这不是最好的做事方式,但我们正在寻找快速解决方案.

这里的内容比我最初的想法更难,我需要做的就是将整个记录复制到MySql自动增量表中的新记录,而无需指定每个字段.这是因为该表可能在将来发生变化,并可能会破坏重复.我将从PHP复制MysqL记录.

这是一个问题,因为在’SELECT *’查询中,MysqL将尝试复制正在复制的记录的ID,这会产生重复的ID错误.

这封锁了:
 INSERT INTO客户SELECT * FROM customer WHERE customerid = 9181.它还阻止了INSERT INTO客户(Field1,Field2,…)SELECT Field1,….. FROM customer WHERE customerid = 9181.

有没有办法从PHPMysqL做到这一点?

最佳答案
我终于找到了这段代码.我相信它将来会帮助别人.所以这就是.

function DuplicateMysqLRecord ($table,$id_field,$id) {
  // load the original record into an array
  $result = MysqL_query("SELECT * FROM {$table} WHERE {$id_field}={$id}");
  $original_record = MysqL_fetch_assoc($result);

  // insert the new record and get the new auto_increment id
  MysqL_query("INSERT INTO {$table} (`{$id_field}`) VALUES (NULL)");
  $newid = MysqL_insert_id();

  // generate the query to update the new record with the prevIoUs values
  $query = "UPDATE {$table} SET ";
  foreach ($original_record as $key => $value) {
    if ($key != $id_field) {
        $query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'",';
    }
  }
  $query = substr($query,strlen($query)-2); # lop off the extra trailing comma
  $query .= " WHERE {$id_field}={$newid}";
  MysqL_query($query);

  // return the new id
  return $newid;
}

这是文章http://www.epigroove.com/posts/79/how_to_duplicate_a_record_in_mysql_using_php链接

原文地址:https://www.jb51.cc/mysql/433833.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐