Php 复制结构未知的MySQL行

Php 复制结构未知的MySQL行,php,mysql,pdo,duplicates,Php,Mysql,Pdo,Duplicates,我试图从一个我技术上一无所知的结构中复制一行 这就是我目前所拥有的。这段代码确实有效,但我很确定这不是最合适的。有人有更好的方法或正确的方法吗?如有任何建议,将不胜感激 /* $table is the table name $id_field is the primary key $id_value is the row I want to copy */ $selectEntity = $dbh->prepare("SELECT * FROM {$table} WH

我试图从一个我技术上一无所知的结构中复制一行

这就是我目前所拥有的。这段代码确实有效,但我很确定这不是最合适的。有人有更好的方法或正确的方法吗?如有任何建议,将不胜感激

/*
   $table is the table name
   $id_field is the primary key
   $id_value is the row I want to copy
*/

$selectEntity = $dbh->prepare("SELECT * FROM {$table} WHERE {$id_field} = :id_value");
$selectEntity->execute(array(':id_value' => $id_value));
$entity = $selectEntity->fetch(PDO::FETCH_ASSOC);

foreach ($entity as &$value){ if(is_null($value) == true) { $value = "NULL"; } else { $value = "'".htmlspecialchars($value, ENT_QUOTES)."'"; } }

//remove the primary key
$entity[$id_field] = "'"; // the ' was the only way I could get NULL to get in there

$insertCloned = $dbh->prepare("INSERT INTO {$table} (".implode(", ",array_keys($entity)).") VALUES ('".implode(", ",array_values($entity)).")");
$insertCloned->execute();
$lastInsertedID = $dbh->lastInsertId();

它非常混乱。

您的引用不正确--您在整个
值列表中都有引号,它们应该在每个单独的值周围。另外,您应该使用
$dbh->escape($value)
来转义这些值
htmlspecialchars
用于在网页上按字面意思显示HTML时对其进行编码

但最好使用查询参数,而不是替换到SQL中。所以试试这个:

$entity[$id_field] = null;
$params = implode(', ', array_fill(0, count($entity), '?'));
$insertCloned = $dbh->prepare("INSERT INTO {$table} VALUES ($params)");
$insertCloned->execute(array_values($entity));

当值与表架构的顺序相同时,不需要在
INSERT
语句中列出列名。由于您首先使用了
SELECT*
来获取值,它们将是。

Hmm。感谢@Barmar的帮助,但我得到了一个
数组到字符串的转换
error/
Column not found:1054未知列“Array”
Oops,忘了将其内爆为字符串。固定的。