Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php and mysql copy record from one table to another

Tags:

php

copy

mysql

I would like to archive a student by moving the record from one table to another. This is the code I am trying to use:

<?php
ini_set('memory_limit', '100M');
$sql="Select * from `register` where student_id=".$student_id;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);

//Call the function to archive the table
//Function definition is given below
archive_record(archive,$row);

//Once you archive, delete the record from original table

$sql = "Delete from `register` where student_id=".$student_id;
mysql_query($sql);


function archive_record($archived_tablename,$row)
{
    $sql = "insert into $archived_tablename values(";
    $i=0;
    while($i<(count($row)-1))
    {
        $sql.="'".$row[$i]."',";
    }
    $i=$i+1;

    $sql.="'".$row[$i]."'";
    $sql.=")";

    mysql_query($sql);
    return true;
}

Problem I am having is that i am getting error:

Fatal error: Out of memory (allocated 80478208) (tried to allocate 80216043 bytes) in /archive-student.php on line XX

Is there any different way to do this, except for have a column called archive and changing from 0 to 1? This is because I have 30-50 pages selecting the table's records. :)

like image 659
David Passmore Avatar asked Mar 09 '12 20:03

David Passmore


People also ask

How do you copy the record in the table to another table?

The SQL INSERT INTO SELECT Statement The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.


1 Answers

INSERT INTO archive_table
SELECT * FROM original_table WHERE id = 1

simple as that.

If tables have different column number, other layout etc., you will have to specify columns :too

INSERT INTO archive_table(field1, field2, field3)
SELECT field7, field8, field9 FROM original_table WHERE id = 1
like image 132
dev-null-dweller Avatar answered Oct 15 '22 09:10

dev-null-dweller