note 69256 added to ref.mysql

From: Date: Tue, 29 Aug 2006 07:52:58 +0000
Subject: note 69256 added to ref.mysql
Groups: php.notes 
Request: Send a blank email to php-notes+get-116450@lists.php.net to get a copy of this message
Keeping history records usually requires you to duplicate rows. With standard MySQL syntax you can create a query like this: INSERT INTO tablename SELECT * FROM tablename WHERE somefield = 'somevalue' The problem is that this won't work if you are using an auto_numbering key id field. There is no way to do this with standard MySQL syntax and I haven't been able to find a standard php function as well. So here's the function I wrote for that very purpose: <?php // function to create a duplicate record in a table with 1 auto_increment id. function mysql_duplicate_record($table, $id_field, $id) { // load original record into array $query = 'SELECT * FROM ' . $table . ' WHERE ' . $id_field . ' = ' . $id . ' LIMIT 1;'; $r = mysql_query( $query ) or die('Error, query failed. ' . mysql_error()); $ar = mysql_fetch_array( $r, MYSQL_ASSOC ); // insert new record and get new auto_increment id mysql_query ('LOCK TABLES ' . $table . ' WRITE;') or die('Error, query failed. ' . mysql_error()); mysql_query ('INSERT INTO ' . $table . ' ( ' . $id_field . ' ) VALUES ( NULL );') or die('Error, query failed. ' . mysql_error()); $id = mysql_insert_id(); mysql_query ('UNLOCK TABLES;') or die('Error, query failed. ' . mysql_error()); // update new record with values from previous record $query = 'UPDATE ' . $table . ' SET '; while ($value = current($ar)) { if (key($ar) != $id_field) { $query .= ''.key($ar).' = "'.$value.'", '; } next($ar); } $query = substr($query,0,strlen($query)-2).' '; $query .= 'WHERE ' . $id_field . ' = "' . $id . '" LIMIT 1;'; mysql_query($query) or die('Error, query failed. ' . mysql_error()); // return the new id return $id; } ?> ---- Server IP: 194.109.193.119 Probable Submitter: 86.83.234.184 ---- X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER autolearn=no version=2.64 ---- Manual Page -- http://www.php.net/manual/en/ref.mysql.php Edit -- https://master.php.net/note/edit/69256 Del: integrated -- https://master.php.net/note/delete/69256/integrated Del: useless -- https://master.php.net/note/delete/69256/useless Del: bad code -- https://master.php.net/note/delete/69256/bad+code Del: spam -- https://master.php.net/note/delete/69256/spam Del: non-english -- https://master.php.net/note/delete/69256/non-english Del: in docs -- https://master.php.net/note/delete/69256/in+docs Del: other reasons-- https://master.php.net/note/delete/69256 Reject -- https://master.php.net/note/reject/69256 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#116450) next »