Posted By

fackz on 10/26/10


Tagged

mysql table backup copy


Versions (?)

Who likes this?

6 people have marked this snippet as a favorite

fackz
luman
ArbaouiMehdi
pytheas
thomas-h
Priestd09


PHP script to make a backup copy of a MySQL table


 / Published in: PHP
 

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

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.

  1. <?php
  2.  
  3. mysql_connect('localhost', 'test', '123456');
  4.  
  5. if(copy_table('products', 'products_bak')) {
  6. echo "success\n";
  7. }
  8. else {
  9. echo "failure\n";
  10. }
  11.  
  12. function copy_table($from, $to) {
  13.  
  14. if(table_exists($to)) {
  15. $success = false;
  16. }
  17. else {
  18. mysql_query("CREATE TABLE $to LIKE $from");
  19. mysql_query("INSERT INTO $to SELECT * FROM $from");
  20. $success = true;
  21. }
  22.  
  23. return $success;
  24.  
  25. }
  26.  
  27. function table_exists($tablename, $database = false) {
  28.  
  29. if(!$database) {
  30. $res = mysql_query("SELECT DATABASE()");
  31. $database = mysql_result($res, 0);
  32. }
  33.  
  34. $res = mysql_query("
  35. SELECT COUNT(*) AS count
  36. FROM information_schema.tables
  37. WHERE table_schema = '$database'
  38. AND table_name = '$tablename'
  39. ");
  40.  
  41. return mysql_result($res, 0) == 1;
  42. }
  43.  
  44.  
  45. ?>

Report this snippet  

You need to login to post a comment.