复制结构未知的MySQL行

I'm trying to copy a row from a structure I technically know nothing about.

This is what I have so far. This code does work but I'm pretty sure this isn't the most appropriate. Anyone have a better way or a right way of doing this? Any suggestions would be appreciated.

/*
   $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();

It's very messy.

Your quoting is not correct -- you have quotes around the entire VALUES list, they should be around each individual value. Also, you should use $dbh->escape($value) to escape the values; htmlspecialchars is for encoding HTML when you want to display it literally on a web page.

But it's better to use query parameters rather than substituting into the SQL. So try this:

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

You don't need to list the column names in the INSERT statement when the values are in the same order as the table schema. And since you used SELECT * to get the values in the first place, they will be.