MySQL PDO backup function

this function is here http://davidwalsh.name/backup-mysql-database-php

floats around the internet for a while and is quite famous, but in standard mysql. Does anyone have the same thing but in PDO? if not someone wants to do it? it's even possible, I read somewhere that PDO does not do SHOW CREATE TABLE - is that right?

Finally, can anyone explain what the difference is between this function and use SELECT * INTO OUTFILE?

(please do not put this to contain too many questions, they are all closely related and I am sure that the answer will be useful to many people)

+4
source share
7 answers

For anyone looking for a function that acts like mysqldump, here is the latest project, with the flaws discussed in the comments above / below, anti-aliasing. Enjoy it.

require 'login.php'; $DBH = new PDO("mysql:host=$db_hostname;dbname=$db_database; charset=utf8", $db_username, $db_password); //put table names you want backed up in this array. //leave empty to do all $tables = array(); backup_tables($DBH, $tables); function backup_tables($DBH, $tables) { $DBH->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL ); //Script Variables $compression = false; $BACKUP_PATH = ""; $nowtimename = time(); //create/open files if ($compression) { $zp = gzopen($BACKUP_PATH.$nowtimename.'.sql.gz', "a9"); } else { $handle = fopen($BACKUP_PATH.$nowtimename.'.sql','a+'); } //array of all database field types which just take numbers $numtypes=array('tinyint','smallint','mediumint','int','bigint','float','double','decimal','real'); //get all of the tables if(empty($tables)) { $pstm1 = $DBH->query('SHOW TABLES'); while ($row = $pstm1->fetch(PDO::FETCH_NUM)) { $tables[] = $row[0]; } } else { $tables = is_array($tables) ? $tables : explode(',',$tables); } //cycle through the table(s) foreach($tables as $table) { $result = $DBH->query("SELECT * FROM $table"); $num_fields = $result->columnCount(); $num_rows = $result->rowCount(); $return=""; //uncomment below if you want 'DROP TABLE IF EXISTS' displayed //$return.= 'DROP TABLE IF EXISTS `'.$table.'`;'; //table structure $pstm2 = $DBH->query("SHOW CREATE TABLE $table"); $row2 = $pstm2->fetch(PDO::FETCH_NUM); $ifnotexists = str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $row2[1]); $return.= "\n\n".$ifnotexists.";\n\n"; if ($compression) { gzwrite($zp, $return); } else { fwrite($handle,$return); } $return = ""; //insert values if ($num_rows){ $return= 'INSERT INTO `'."$table"."` ("; $pstm3 = $DBH->query("SHOW COLUMNS FROM $table"); $count = 0; $type = array(); while ($rows = $pstm3->fetch(PDO::FETCH_NUM)) { if (stripos($rows[1], '(')) {$type[$table][] = stristr($rows[1], '(', true); } else $type[$table][] = $rows[1]; $return.= "`".$rows[0]."`"; $count++; if ($count < ($pstm3->rowCount())) { $return.= ", "; } } $return.= ")".' VALUES'; if ($compression) { gzwrite($zp, $return); } else { fwrite($handle,$return); } $return = ""; } $count =0; while($row = $result->fetch(PDO::FETCH_NUM)) { $return= "\n\t("; for($j=0; $j<$num_fields; $j++) { //$row[$j] = preg_replace("\n","\\n",$row[$j]); if (isset($row[$j])) { //if number, take away "". else leave as string if ((in_array($type[$table][$j], $numtypes)) && (!empty($row[$j]))) $return.= $row[$j] ; else $return.= $DBH->quote($row[$j]); } else { $return.= 'NULL'; } if ($j<($num_fields-1)) { $return.= ','; } } $count++; if ($count < ($result->rowCount())) { $return.= "),"; } else { $return.= ");"; } if ($compression) { gzwrite($zp, $return); } else { fwrite($handle,$return); } $return = ""; } $return="\n\n-- ------------------------------------------------ \n\n"; if ($compression) { gzwrite($zp, $return); } else { fwrite($handle,$return); } $return = ""; } $error1= $pstm2->errorInfo(); $error2= $pstm3->errorInfo(); $error3= $result->errorInfo(); echo $error1[2]; echo $error2[2]; echo $error3[2]; if ($compression) { gzclose($zp); } else { fclose($handle); } } 
+7
source

This backup script is ridiculous and no one should make another version of it. I saw the script before, as well as similar attempts, and they have a lot of problems:

  • Doesn't limit table names in reverse tick
  • Does not handle null
  • Doesn't handle character set
  • Does not process binary data
  • Doesn't back up VIEWs
  • Does not back up TRIGGERS or REMEMBERED PROCEDURES OR CORRECTED FUNCTIONS OR EVENTS
  • Uses the legacy mysql extension (but that’s why you want the PDO version, right?)
  • Uses addlashes () instead of the correct MySQL acceleration function.
  • Adds all data for all tables to one very long row before displaying all the content. This means that you should be able to store your entire database on one line, which will almost certainly remove your maximum PHP memory limit.

See also my last answer about the failed David Walsh backup script:


Your comment:

Read the comments on the page you linked to. Many people have identified problems, and some have fixes, or at least suggestions.

The fact that this script adds everything to one line is, it seems to me, a transaction break, but it’s easy to modify the script to open the output file first, and then output the data of each line during the loop, then close the file after the loop. This is not a problem, I'm not sure why the script does not. But it is pretty clear that the script has not been tested very well.

But in any case, I would not invent this wheel. Mysqldump or mydumper do an excellent job of this. FWIW, you do not need to run mysqldump on the same server as the database. Mysqldump supports the --host option, so you can run mysqldump anywhere to back up the remote database if firewalls do not block your client connection. Basically, if you can connect a PHP application to the database from some client host, you can connect mysqldump.

If this is really not an option, I would use the phpmyadmin database dump function. They are mature and well tested, and they dump everything correctly. Here is an article that describes how to use the dump function:

http://www.techrepublic.com/blog/smb-technologist/import-and-export-databases-using-phpmyadmin/


[Copy comments from your answer:]

This gets into code review, which is not the purpose of StackOverflow. But briefly:

  • there is no proper NULL support (you convert them to ``);
  • do not sequentially split table names;
  • the use of double quotes without ANSI as line separators;
  • the use of buffered queries on huge tables will lead to breaking the maximum memory limit PHP max;
  • Adding all the rows for a huge table will break the maximum PHP max memory limit;
  • using addlashes () instead of PDO :: quote ();
  • request error checking only at the end of the function;
  • not checking for file creation with an error;
  • The gzip extension cannot be downloaded
  • In addition, it may still not support UTF8 data.

but he gets there, no?

Yes, this is better than the original David Walsh script. :-)

What is wrong with NULL?

NULL is not the same as in SQL (except Oracle, but in this case they do not comply with the SQL standard). See MySQL, is it better to insert NULL or an empty string?

Table structure

should be very large for maximum memory. each insert line is written to the file separately in the same way, the line must be very large for maximum memory.

I am not reading the code correctly on the issue of memory limitations. You write the output for each line, so everything is fine (unless the line contains a 1GB block or something else).

But you should not just output a single INSERT statement with a comma-separated set of strings. Even mysqldump --extended-insert prints the final data length, then runs a new INSERT statement. The criterion is whether the length of the INSERT statement --net-buffer-length argument parameter for --net-buffer-length .

What is wrong with line separators? how can i get ansi?

In ANSI SQL, single quotes '' are used to delimit string literals or date literals. Double quotes are used to delimit identifiers, such as table or column names. By default, MySQL treats them the same way, but this is non-standard. See Do different databases use different quotes with names?. If you try to import backup data to the MySQL server where you have SET SQL_MODE=ANSI_QUOTES , the import will fail.

and which tables are not split?

Example: query('SELECT * FROM '.$table); and in fact, each of the other cases when you use $ table in a query. You only delimit the table once, in the INSERT statement, the output of the script.

all $ tables are unlimited, should they all be with ""?

MySQL always recognizes back ticks as identifier delimiters and single quotes for strings / dates. But double quotes change the value depending on the SQL_MODE I mentioned. You cannot assume which SQL_MODE acts on the MySQL instance you are restoring to, so it is best to use back ticks for identifiers and single quotes for strings. The reason you split them when querying your table is because you might have table names that are SQL reserved words or that contain special characters, etc.

can you embed float without delimiters in mysql, or is it necessary? thanks

You can insert all numeric types without separators. Only strings and dates need delimiters. See Dev.mysql.com/doc/refman/5.6/en/literals.html

+7
source

All PDO and ext/mysql are wrapping commands for the base database (in this case, MySQL). That is, nothing can stop the PDO from running SHOW CREATE TABLE or other commands.

For all purposes and goals, you can pretty much simply replace:

 - $link = mysql_connect($host,$user,$pass); - mysql_select_db($name,$link); + $link = new PDO("mysql:host=$host;dbname=$name", $user, $pass); 

And instead

 $result = mysql_query($query); mysql_fetch_assoc($result); 

Using

 $result = $link->query($query); $result->fetch(); 
+3
source

As recommended fooobar.com/questions/1497476 / ... use mysqldump with exec . It comes down to the following:

 <?php function importDatabase($host, $user, $password, $database, $backupFilePath) { //returns true iff successfull return exec('mysqlimport --host '. $host .' --user '. $user .' --password '. $password .' '. $database .' '.targetFilePath) === 0; } function exportDatabase($host, $user, $password, $database, $targetFilePath) { //returns true iff successfull return exec('mysqldump --host '. $host .' --user '. $user .' --password '. $password .' '. $database .' --result-file='.targetFilePath) === 0; } 
+2
source

I just finished creating the PDO version of the original david walsh backup function.
I also improved it to answer the questions mentioned in Bill Carvin's answer ; handles NULL, writes single lines, so there is no problem with memory, with backticks, etc.
Throws pretty much what mysqldump does.
Could do with a little clean, but here, please report any improvements

 require 'login.php'; $DBH = new PDO("mysql:host=$db_hostname;dbname=$db_database; charset=utf8", $db_username, $db_password); //put table names you want backed up in this array. //leave empty to do all $tables = array(); backup_tables($DBH, $tables); function backup_tables($DBH, $tables) { $DBH->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_TO_STRING ); //Script Variables $compression = false; $BACKUP_PATH = ""; $nowtimename = time(); //create/open files if ($compression) { $zp = gzopen($BACKUP_PATH.$nowtimename.'.sql.gz', "w9"); } else { $handle = fopen($BACKUP_PATH.$nowtimename.'.sql','a+'); } //array of all database field types which just take numbers $numtypes=array('tinyint','smallint','mediumint','int','bigint','float','double','decimal','real'); //get all of the tables if(empty($tables)) { $pstm1 = $DBH->query('SHOW TABLES'); while ($row = $pstm1->fetch(PDO::FETCH_NUM)) { $tables[] = $row[0]; } } else { $tables = is_array($tables) ? $tables : explode(',',$tables); } //cycle through the table(s) foreach($tables as $table) { $result = $DBH->query('SELECT * FROM '.$table); $num_fields = $result->columnCount(); $num_rows = $result->rowCount(); $return=""; //uncomment below if you want 'DROP TABLE IF EXISTS' displayed //$return.= 'DROP TABLE IF EXISTS `'.$table.'`;'; //table structure $pstm2 = $DBH->query('SHOW CREATE TABLE '.$table); $row2 = $pstm2->fetch(PDO::FETCH_NUM); $ifnotexists = str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $row2[1]); $return.= "\n\n".$ifnotexists.";\n\n"; if ($compression) { gzwrite($zp, $return); } else { fwrite($handle,$return); } $return = ""; //insert values if ($num_rows){ $return= 'INSERT INTO `'.$table."` ("; $pstm3 = $DBH->query('SHOW COLUMNS FROM '.$table); $count = 0; $type = array(); while ($rows = $pstm3->fetch(PDO::FETCH_NUM)) { if (stripos($rows[1], '(')) {$type[$table][] = stristr($rows[1], '(', true); } else $type[$table][] = $rows[1]; $return.= $rows[0]; $count++; if ($count < ($pstm3->rowCount())) { $return.= ", "; } } $return.= ")".' VALUES'; if ($compression) { gzwrite($zp, $return); } else { fwrite($handle,$return); } $return = ""; } while($row = $result->fetch(PDO::FETCH_NUM)) { $return= "\n\t("; for($j=0; $j<$num_fields; $j++) { $row[$j] = addslashes($row[$j]); //$row[$j] = preg_replace("\n","\\n",$row[$j]); if (isset($row[$j])) { //if number, take away "". else leave as string if (in_array($type[$table][$j], $numtypes)) $return.= $row[$j] ; else $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; } if ($j<($num_fields-1)) { $return.= ','; } } $count++; if ($count < ($result->rowCount())) { $return.= "),"; } else { $return.= ");"; } if ($compression) { gzwrite($zp, $return); } else { fwrite($handle,$return); } $return = ""; } $return="\n\n-- ------------------------------------------------ \n\n"; if ($compression) { gzwrite($zp, $return); } else { fwrite($handle,$return); } $return = ""; } $error1= $pstm2->errorInfo(); $error2= $pstm3->errorInfo(); $error3= $result->errorInfo(); echo $error1[2]; echo $error2[2]; echo $error3[2]; if ($compression) { gzclose($zp); } else { fclose($handle); } } 
+1
source
 function backupDB() { $db_config = getDbConfigFromWordPress(); if ($db_config === false) { unset($db_config); logMessage('Unable to get database configuration from WordPress', true, 'red'); return false; } $new_backup_file = __DIR__ . DIRECTORY_SEPARATOR . 'newbackup_xxx_date.sql'; if (is_file($new_backup_file) && is_writable($new_backup_file)) { @unlink($new_backup_file); } elseif (is_file($new_backup_file) && !is_writable($new_backup_file)) { logMessage('Unable to remove new backup SQL file. This is necessary to create backup SQL file.', true, 'red'); return false; } unset($new_backup_file); $dbh = new \PDO('mysql:dbname=' . $db_config['dbname'] . ';host=' . $db_config['dbhost'] . ';charset=' . $db_config['dbcharset'], $db_config['dbuser'], $db_config['dbpassword']); $dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); $dbh->setAttribute(\PDO::ATTR_DEFAULT_FETCH_MODE, \PDO::FETCH_OBJ); $dbh->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true); $sth = $dbh->prepare('SHOW TABLES'); $sth->execute(); $result = $sth->fetchAll(\PDO::FETCH_COLUMN); $tables = []; if (is_array($result) && !empty($result)) { foreach ($result as $row) { if (is_string($row) && stristr($row, $db_config['tableprefix']) !== false) { $tables[] = $row; } elseif (is_array($row) && array_key_exists(0, $row) && stristr($row[0], $db_config['tableprefix']) !== false) { $tables[] = $row[0]; } }// endforeach; natcasesort($tables); } $sth->closeCursor(); unset($result, $row, $sth); // begins export string header. $export_sql = '-- Manual backup SQL Dump'."\n\n"; $export_sql .= 'SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";'."\n\n\n"; $export_sql .= '--'."\n"; $export_sql .= '-- Database: `' . $db_config['dbname'] . '`'."\n"; $export_sql .= '--'."\n\n"; unset($db_config); writeDownBackupDB($export_sql); unset($export_sql); // starting to loop thru tables. if (isset($tables) && is_array($tables)) { foreach ($tables as $table) { $export_sql = '-- --------------------------------------------------------'."\n\n"; $export_sql .= '--'."\n"; $export_sql .= '-- Table structure for table `' . $table . '`'."\n"; $export_sql .= '--'."\n\n"; $export_sql .= 'DROP TABLE IF EXISTS `' . $table . '`;'."\n"; $sth = $dbh->prepare('SHOW CREATE TABLE `' . $table . '`'); $sth->execute(); $row = $sth->fetch(\PDO::FETCH_NUM); if (isset($row[1])) { $create_sql_string = $row[1]; $create_sql_string = str_replace(['CREATE TABLE `'], ['CREATE TABLE IF NOT EXISTS `'], $create_sql_string); if (substr($create_sql_string, -1) != ';') { $create_sql_string .= ' ;'; } } else { $create_sql_string = ''; } unset($row); $export_sql .= $create_sql_string."\n\n"; $sth->closeCursor(); unset($sth); writeDownBackupDB($export_sql); unset($export_sql); $export_sql = '--'."\n"; $export_sql .= '-- Dumping data for table `' . $table . '`'."\n"; $export_sql .= '--'."\n\n"; writeDownBackupDB($export_sql); unset($export_sql); // get fields $sth = $dbh->prepare('SELECT * FROM `' . $table . '` LIMIT 1'); $sth->execute(); $result = $sth->fetch(\PDO::FETCH_ASSOC); if (is_array($result)) { $fields = array_keys($result); } else { $fields = []; } $sth->closeCursor(); unset($result, $sth); // get fields type $sth = $dbh->prepare('DESCRIBE `' . $table . '`'); $sth->execute(); $table_columns = $sth->fetchAll(); $columns = []; if (is_array($table_columns)) { foreach ($table_columns as $column) { $columns[$column->Field] = [ 'field' => $column->Field, 'type' => $column->Type, 'null' => $column->Null, 'default' => $column->Default, ]; }// endforeach; unset($column); } $sth->closeCursor(); unset($sth, $table_columns); if (isset($fields) && is_array($fields) && !empty($fields)) { $select_string = 'SELECT '; $i_count_field = 1; foreach ($fields as $field) { $select_string .= 'IF (`' . $field . '` IS NULL, \'FIELD_VALUE_NULL\', `' . $field . '`) AS `' . $field . '`'; if ($i_count_field < count($fields)) { $select_string .= ', '; } $i_count_field++; }// endforeach; unset($i_count_field, $field); $select_string .= ' FROM `' . $table . '`'; $sth = $dbh->prepare($select_string); unset($select_string); $sth->execute(); $result = $sth->fetchAll(); $export_sql = ''; if (is_array($result) && !empty($result)) { // generate INSERT INTO `table_name` string. $export_sql .= 'INSERT INTO `' . $table . '` ('; $i_count = 1; foreach ($fields as $field) { $export_sql .= '`' . $field . '`'; if ($i_count < count($fields)) { $export_sql .= ', '; } $i_count++; }// endforeach; unset($field, $i_count); $export_sql .= ') VALUES'."\n"; writeDownBackupDB($export_sql); unset($export_sql); // generate VALUES of INSERT INTO. if (is_array($result)) { $i_count = 1; $i_count_break = 1; foreach ($result as $row) { $export_sql = '('; $i_count_fields = 1; foreach ($fields as $field) { $field_value = $row->{$field}; // escape slash $field_value = str_replace('\\', '\\\\', $field_value); // sanitize new line $field_value = str_replace(["\r\n", "\r", "\n"], ['\r\n', '\r', '\n'], $field_value); // escape single quote $field_value = str_replace('\'', '\'\'', $field_value); // change value to NULL if it is NULL. if ($field_value === 'FIELD_VALUE_NULL') { $field_value = 'NULL'; } // detect field value type and cloak with single quote. if (isset($columns[$field]['type']) && ( stristr($columns[$field]['type'], 'tinyint(') !== false || stristr($columns[$field]['type'], 'smallint(') !== false || stristr($columns[$field]['type'], 'mediumint(') !== false || stristr($columns[$field]['type'], 'int(') !== false || stristr($columns[$field]['type'], 'bigint(') !== false ) ) { // this field column type is int if (!is_numeric($field_value) && $field_value !== 'NULL') { $field_value = '\'' . $field_value . '\''; } } else { if ($field_value !== 'NULL') { $field_value = '\'' . $field_value . '\''; } } $export_sql .= $field_value; unset($field_value); if ($i_count_fields < count($fields)) { $export_sql .= ', '; } $i_count_fields++; }// endforeach; unset($field, $i_count_fields); $export_sql .= ')'; if ($i_count < count($result)) { if ($i_count_break >= 30) { $export_sql .= ';'."\n"; writeDownBackupDB($export_sql); unset($export_sql); $i_count_break = 0; $export_sql = 'INSERT INTO `' . $table . '` ('; $i_count_fields = 1; foreach ($fields as $field) { $export_sql .= '`' . $field . '`'; if ($i_count_fields < count($fields)) { $export_sql .= ', '; } $i_count_fields++; }// endforeach; unset($field, $i_count_fields); $export_sql .= ') VALUES'."\n"; writeDownBackupDB($export_sql); unset($export_sql); $export_sql = ''; } else { $export_sql .= ','."\n"; } } else { $export_sql .= ';'."\n\n"; } $i_count++; $i_count_break++; writeDownBackupDB($export_sql); unset($export_sql); }// endforeach; unset($i_count, $i_count_break, $result, $row); } } else { $export_sql .= "\n"; writeDownBackupDB($export_sql); unset($export_sql); } unset($fields); $sth->closeCursor(); unset($result, $sth); } else { $export_sql = "\n"; writeDownBackupDB($export_sql); unset($export_sql); } unset($export_sql); }// endforeach; unset($table); } unset($tables); unset($dbh); logMessage('Backup DB completed. Max memory usage is ' . formatBytes(memory_get_peak_usage(true)) . '.', true, 'green'); return true; }// backupDB /** * Write content to backup SQL file by append. * * @param string $content */ function writeDownBackupDB($content) { $new_backup_file = __DIR__ . DIRECTORY_SEPARATOR . 'newbackup_xxx_date.sql'; $handle = fopen($new_backup_file, 'a+'); fwrite($handle, $content); fclose($handle); unset($handle, $new_backup_file); }// writeDownBackupDB logMessage('Beginning backup DB.', true, 'light_gray'); backupDB(); 

Note that...

  • Some functions are missing, for example logMessage() , getDbConfigFromWordPress() . Remove it before using it.
  • Something like $db_config['tableprefix'] or $db_config[...] should be changed.
  • There are many things that cannot be handled like @Bill Karwin .
  • I am not sure that it supports UTF-8 data, but as I see it is support for many languages, as well as support for emoji (πŸ˜‚πŸ˜­πŸ˜).
  • Exporting with the mysql command is always better.
0
source

I implemented the latest version of Lan with a few changes (see code below):

  • Tables are saved in a folder named date date; previous versions of the same day are overwritten.
  • It supports several formats, including comma-delimited CSV
  • It displays table sizes in bytes and row numbers
  • Using my (true old-fashioned) tables

The reason for adding the csv option is that I was not able to import TEXT (UTF8) data from SQL files when it is multibyte (Asian scripts). It really works with the BLOB format, but we cannot index it as FULLTEXT. I probably missed the point in table formatting ...

Here is the code anyway:

 function backup_tables($DBH,$tables,$compression,$format) { $DBH->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL ); //Script Variables $BACKUP_PATH = DUMP; $date = date("Ymd"); $olddir = getcwd(); chdir($BACKUP_PATH); if(!file_exists($date)) { echo "<font color=red>Created '".$date."' folder</font><br />"; $cmd = "mkdir ".$date; exec($cmd); } chdir($date); //array of all database field types which just take numbers $numtypes = array('tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'float', 'double', 'decimal', 'real'); //get all of the tables if(empty($tables)) { $pstm1 = $DBH->query('SHOW TABLES'); while($row = $pstm1->fetch(PDO::FETCH_NUM)) { $tables[] = $row[0]; } } else { $tables = is_array($tables) ? $tables : explode(',',$tables); } //cycle through the table(s) echo "<font color=blue>Dumping tables to DB_DUMP:</font>"; echo "<ul>"; foreach($tables as $table) { //create/open files if($format == "csv") { $filename = $table.".csv"; $handle = fopen($filename,"w"); } else { if($compression) { $filename = $table.".sql.gz"; $zp = gzopen($filename,"wb9"); } else { $filename = $table.".sql"; $handle = fopen($filename,"w"); } } echo "<li><small><font color=blue>".$filename."</font>"; $result = $DBH->query("SELECT * FROM $table"); $num_fields = $result->columnCount(); $num_rows = $result->rowCount(); $return = ""; $return .= 'DROP TABLE IF EXISTS `'.$table.'`;'; //table structure $pstm2 = $DBH->query("SHOW CREATE TABLE $table"); $row2 = $pstm2->fetch(PDO::FETCH_NUM); $ifnotexists = str_replace('CREATE TABLE', 'CREATE TABLE IF NOT EXISTS', $row2[1]); $return .= "\n\n".$ifnotexists.";\n\n"; if($format <> "csv") { if($compression) gzwrite($zp, $return); else fwrite($handle,$return); } $return = ""; //insert values if($num_rows) { $return = 'INSERT INTO `'."$table"."` ("; $pstm3 = $DBH->query("SHOW COLUMNS FROM $table"); $count = 0; $type = array(); while($rows = $pstm3->fetch(PDO::FETCH_NUM)) { if(stripos($rows[1], '(')) { $type[$table][] = stristr($rows[1], '(', true); } else $type[$table][] = $rows[1]; $return .= "`".$rows[0]."`"; $count++; if($count < ($pstm3->rowCount())) { $return .= ", "; } } $return .= ")".' VALUES'; if($format <> "csv") { if($compression) gzwrite($zp, $return); else fwrite($handle,$return); } $return = ""; } $count = 0; while($row = $result->fetch(PDO::FETCH_NUM)) { if($format <> "csv") $return = "\n\t("; for($j=0; $j < $num_fields; $j++) { //$row[$j] = preg_replace("\n","\\n",$row[$j]); if(isset($row[$j])) { if($format == "csv") $return .= '"'.$row[$j].'"'; else { //if number, take away "". else leave as string if((in_array($type[$table][$j],$numtypes)) && (!empty($row[$j]))) $return .= $row[$j]; else $return .= $DBH->quote($row[$j]); } } else { if($format == "csv") $return .= ''; else $return .= 'NULL'; } if($j < ($num_fields-1)) $return .= ','; } $count++; if($format == "csv") $return .= "\n"; else { if($count < ($result->rowCount())) $return .= "),"; else $return .= ");"; } if($format == "csv") fwrite($handle,$return); else { if($compression) gzwrite($zp, $return); else fwrite($handle,$return); } $return = ""; } $return = "\n\n-- ------------------------------------------------ \n\n"; echo " (".$count." records)"; if($format <> "csv") { if($compression) gzwrite($zp, $return); else fwrite($handle,$return); } $return = ""; $error1 = $pstm2->errorInfo(); $error2 = $pstm3->errorInfo(); $error3 = $result->errorInfo(); echo $error1[2]; echo $error2[2]; echo $error3[2]; if($format == "csv") fclose($handle); else { if($compression) gzclose($zp); else fclose($handle); } $filesize = filesize($filename); echo " - ".$filesize." bytes</small></li>"; } echo "</ul>"; chdir($olddir); return; } 
0
source

Source: https://habr.com/ru/post/1497476/


All Articles