Return to Snippet

Revision: 34621
at October 26, 2010 04:07 by fackz


Initial Code
<?php

mysql_connect('localhost', 'test', '123456');
mysql_select_db('test');

if(copy_table('products', 'products_bak')) {
    echo "success\n";
}
else {
    echo "failure\n";
}

function copy_table($from, $to) {

    if(table_exists($to)) {
        $success = false;
    }
    else {
        mysql_query("CREATE TABLE $to LIKE $from");
        mysql_query("INSERT INTO $to SELECT * FROM $from");
        $success = true;
    }
   
    return $success;
   
}

function table_exists($tablename, $database = false) {

    if(!$database) {
        $res = mysql_query("SELECT DATABASE()");
        $database = mysql_result($res, 0);
    }
   
    $res = mysql_query("
        SELECT COUNT(*) AS count
        FROM information_schema.tables
        WHERE table_schema = '$database'
        AND table_name = '$tablename'
    ");
   
    return mysql_result($res, 0) == 1;
}


?>

Initial URL
http://www.electrictoolbox.com/php-script-backup-copy-mysql-table/

Initial Description
The script below connects to a MySQL database server on "localhost" using the login name "test" and password "123456" and then connects to the database "test". It then copies the table structure and data from the table "products" to a new table "products_bak". If the target table already exists the function returns false.

Initial Title
PHP script to make a backup copy of a MySQL table

Initial Tags
mysql, table, backup, copy

Initial Language
PHP