MySQL SQL Importer


SUBMITTED BY: Guest

DATE: Nov. 16, 2013, 10:31 a.m.

FORMAT: PHP

SIZE: 2.7 kB

HITS: 31921

  1. <?php
  2. class DBImporter {
  3. /**
  4. * @access private
  5. */
  6. var $database = null;
  7. var $connection = null;
  8. var $compress = null;
  9. var $utf8 = null;
  10. var $importFilename = null;
  11. /**
  12. * Class constructor
  13. * @param string $db The database name
  14. * @param string $connection The database connection handler
  15. * @param boolean $compress It defines if the output/import file is compressed (gzip) or not
  16. * @param string $filepath The file where the dump will be written
  17. */
  18. public static function Setup($db=null, $connection=null, $filepath='dump.sql', $compress=false) {
  19. $this->connection = $connection;
  20. $this->compress = $compress;
  21. $this->importFilename = $filepath;
  22. $this->utf8 = true;
  23. return $this->setDatabase($db);
  24. }
  25. /**
  26. * Sets the database to work on
  27. * @param string $db The database name
  28. */
  29. function setDatabase($db){
  30. $this->database = $db;
  31. if ( !@mysql_select_db($this->database) )
  32. return false;
  33. return true;
  34. }
  35. /**
  36. * Read from SQL file and make sql query
  37. */
  38. function importSql($file) {
  39. // Reading SQL from file
  40. echo "Reading SQL from file '".$this->importFilename."': ";
  41. if ($this->compress) {
  42. $lines = gzfile($file);
  43. }
  44. else {
  45. $lines = file($file);
  46. }
  47. echo " DONE!\n";
  48. echo "Importing SQL into database '".$this->database."': ";
  49. $x = 0;
  50. $importSql = "";
  51. $procent = 0;
  52. foreach ($lines as $line) {
  53. // Print progress
  54. $x++;
  55. $numOfLines = count($lines);
  56. if ($x%(int)($numOfLines/20) == 0) {
  57. $procent += 5;
  58. if ($procent%25 == 0) echo "$procent%";
  59. else echo ".";
  60. }
  61. // Importing SQL
  62. $importSql .= $line;
  63. if ( substr(trim($line), strlen(trim($line))-1) == ";" ) {
  64. $query = @mysql_query($importSql, $this->connection);
  65. if (!$query) return false;
  66. $importSql = "";
  67. }
  68. }
  69. return true;
  70. }
  71. /**
  72. * Import SQL file into selected database
  73. */
  74. public static function doImport() {
  75. if ( !$this->setDatabase($this->database) )
  76. return false;
  77. if ( $this->utf8 ) {
  78. $encoding = @mysql_query("SET NAMES 'utf8'", $this->connection);
  79. }
  80. if ( $this->importFilename ) {
  81. $import = $this->importSql($this->importFilename);
  82. if (!$import) echo "\n".mysql_error($this->connection)."\n";
  83. else echo " DONE!\n";
  84. return $import;
  85. }
  86. else {
  87. return false;
  88. }
  89. }
  90. function sayHello() {
  91. echo "hoy import";
  92. }
  93. }
  94. ?>

comments powered by Disqus