insert into table select * from table where primarykey=1
I just want to copy one row to insert into the same table (i.e., I want to duplicate an ex
Just wanted to post my piece of PHP code, because I think the way I collect the columns is a bit cleaner in code than the previous examples. Also this shows how you could easily alter an field, in this case adding a string. But you could also replace a foreign key field with the newly added record, in case you want to copy some child records as well.
// Read columns, unset the PK (always the first field in my case)
$stmt = $conn->prepare('SHOW COLUMNS FROM template');
$stmt->execute();
$columns = $stmt->fetchAll();
$columns = array_map(function ($element) { return $element['Field']; }, $columns);
unset($columns[0]);
// Insert record in the database. Add string COPY to the name field.
$sql = "INSERT INTO `template` (".implode(",", $columns).")";
if ($key = array_search('name', $columns))
$columns[$key] = "CONCAT(name, ' COPY')";
$sql .= " SELECT ".implode(",", $columns)." FROM `template` WHERE `id` = ".$id;
$stmt = $conn->prepare($sql);
$stmt->execute();