title: Duplicate MYSQL Record with child records
body: <p>I am using the code below to duplicate a event record in my database, problem is I am trying to also duplicate any child records (i.e. event services). I need it to copy all "event services" from the eventservices table as well as update the eventid during copy to the newly copied id record. Any help would be appreciated. Thanks.</p>
  
  <p>Note: The eventservices table has a eventid field which matches the id of the event.</p>
  
  <pre><code>$table = 'events';
  $id_field = 'id';
  $id = $_GET['eventid'];
  DuplicateMySQLRecord($table, $id_field, $id);
  
  
  
  function DuplicateMySQLRecord($table, $id_field, $id) {
  
          include_once 'db_connect.php';
        // 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 =&gt; $value) {
          if ($key != $id_field) {
              $query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'", ';
          }
        }
        $query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma
        $query .= " WHERE {$id_field}={$newid}";
        mysql_query($query);
  
        // return the new id
        return $newid;
  
      }
  </code></pre>