drcrc28428 2018-02-01 16:13
浏览 125
已采纳

如何复制mySQL表行但插入一个自定义值?

With this code I am duplicating my table row:

 $old_name = "Laura";
 $new_name = "Sam";

 $pdo = $db->prepare('INSERT INTO animals (status, name) SELECT status, name FROM animals WHERE name = :name');
 $pdo->execute(array(
        ':name' => $old_name,
  )); 

It is working well, but I need to put on the position of name by the new insert a custom value.

This is my approach:

 $old_name = "Laura";
 $new_name = "Sam";

 $pdo = $db->prepare('INSERT INTO animals (status, name) values(:name) SELECT status, name FROM animals WHERE name = :name');
 $pdo->execute(array(
        ':name' => $new_name,
        ':name' => $old_name,
  )); 

The error message is:

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax

  • 写回答

1条回答 默认 最新

  • dongmeng1868 2018-02-01 16:26
    关注

    You don't need VALUES() with INSERT SELECT and there's probably some ambiguity on the column names since you're both selecting from, and inserting to, the same table - so you should alias one of them.

    Also, since you're entering different values on the :name placeholder, you're going to need two different placeholders.

    This should probably do it:

    $old_name = "Laura";
    $new_name = "Sam";
    
    $pdo = $db->prepare('INSERT INTO animals(animals.status, animals.name) SELECT a.status, :new_name FROM animals AS a WHERE a.name = :old_name');
    $pdo->execute(array(
        ':old_name' => $old_name,
        ':new_name' => $new_name,
    ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算