with full exportar ejemplo desde php mysql backup

full - Exportar base de datos MySQL usando solo PHP



php backup full mysql database (11)

échale un vistazo a este enlace

http://davidwalsh.name/backup-mysql-database-php

o este

Clase PHP para exportar / importar datos de MySQL

¿Alguien tiene un tutorial para exportar una base de datos MySQL a un archivo .sql? No tengo acceso de shell, así que no puedo usar el código. Encontré este URL: http://davidwalsh.name/backup-mysql-database-php pero revisé el código y este código es antiguo y no es bueno. escrito. He buscado en Internet, pero para la mayoría de los tutoriales necesito acceso a shell, el resto está desactualizado.

Gracias por adelantado.


Aquí está mi código. Esto hará una copia de seguridad de la base de datos MySQL y la almacenará en la ruta especificada.

<?php function backup_mysql_database($options){ $mtables = array(); $contents = "-- Database: `".$options[''db_to_backup'']."` --/n"; $mysqli = new mysqli($options[''db_host''], $options[''db_uname''], $options[''db_password''], $options[''db_to_backup'']); if ($mysqli->connect_error) { die(''Error : (''. $mysqli->connect_errno .'') ''. $mysqli->connect_error); } $results = $mysqli->query("SHOW TABLES"); while($row = $results->fetch_array()){ if (!in_array($row[0], $options[''db_exclude_tables''])){ $mtables[] = $row[0]; } } foreach($mtables as $table){ $contents .= "-- Table `".$table."` --/n"; $results = $mysqli->query("SHOW CREATE TABLE ".$table); while($row = $results->fetch_array()){ $contents .= $row[1].";/n/n"; } $results = $mysqli->query("SELECT * FROM ".$table); $row_count = $results->num_rows; $fields = $results->fetch_fields(); $fields_count = count($fields); $insert_head = "INSERT INTO `".$table."` ("; for($i=0; $i < $fields_count; $i++){ $insert_head .= "`".$fields[$i]->name."`"; if($i < $fields_count-1){ $insert_head .= '', ''; } } $insert_head .= ")"; $insert_head .= " VALUES/n"; if($row_count>0){ $r = 0; while($row = $results->fetch_array()){ if(($r % 400) == 0){ $contents .= $insert_head; } $contents .= "("; for($i=0; $i < $fields_count; $i++){ $row_content = str_replace("/n","//n",$mysqli->real_escape_string($row[$i])); switch($fields[$i]->type){ case 8: case 3: $contents .= $row_content; break; default: $contents .= "''". $row_content ."''"; } if($i < $fields_count-1){ $contents .= '', ''; } } if(($r+1) == $row_count || ($r % 400) == 399){ $contents .= ");/n/n"; }else{ $contents .= "),/n"; } $r++; } } } if (!is_dir ( $options[''db_backup_path''] )) { mkdir ( $options[''db_backup_path''], 0777, true ); } $backup_file_name = $options[''db_to_backup''] . " sql-backup- " . date( "d-m-Y--h-i-s").".sql"; $fp = fopen($options[''db_backup_path''] . ''/'' . $backup_file_name ,''w+''); if (($result = fwrite($fp, $contents))) { echo "Backup file created ''--$backup_file_name'' ($result)"; } fclose($fp); return $backup_file_name; } $options = array( ''db_host''=> ''localhost'', //mysql host ''db_uname'' => ''root'', //user ''db_password'' => '''', //pass ''db_to_backup'' => ''attendance'', //database name ''db_backup_path'' => ''/htdocs'', //where to backup ''db_exclude_tables'' => array() //tables to exclude ); $backup_file_name=backup_mysql_database($options);


En los sistemas * nix, use el comando WHICH para mostrar la ubicación del mysqldump, intente esto:

<?php $dbhost = ''localhost''; $dbuser = ''root''; $dbpass = ''password''; $dbname = ''test''; $mysqldump=exec(''which mysqldump''); $command = "$mysqldump --opt -h $dbhost -u $dbuser -p $dbpass $dbname > $dbname.sql"; exec($command); ?>



La mejor manera de exportar la base de datos usando script php.

O agregue el quinto parámetro (matriz) de tablas específicas: array("mytable1","mytable2","mytable3") para varias tablas

<?php //ENTER THE RELEVANT INFO BELOW $mysqlUserName = "Your Username"; $mysqlPassword = "Your Password"; $mysqlHostName = "Your Host"; $DbName = "Your Database Name here"; $backup_name = "mybackup.sql"; $tables = "Your tables"; //or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3") for multiple tables Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName, $tables=false, $backup_name=false ); function Export_Database($host,$user,$pass,$name, $tables=false, $backup_name=false ) { $mysqli = new mysqli($host,$user,$pass,$name); $mysqli->select_db($name); $mysqli->query("SET NAMES ''utf8''"); $queryTables = $mysqli->query(''SHOW TABLES''); while($row = $queryTables->fetch_row()) { $target_tables[] = $row[0]; } if($tables !== false) { $target_tables = array_intersect( $target_tables, $tables); } foreach($target_tables as $table) { $result = $mysqli->query(''SELECT * FROM ''.$table); $fields_amount = $result->field_count; $rows_num=$mysqli->affected_rows; $res = $mysqli->query(''SHOW CREATE TABLE ''.$table); $TableMLine = $res->fetch_row(); $content = (!isset($content) ? '''' : $content) . "/n/n".$TableMLine[1].";/n/n"; for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0) { while($row = $result->fetch_row()) { //when started (and every after 100 command cycle): if ($st_counter%100 == 0 || $st_counter == 0 ) { $content .= "/nINSERT INTO ".$table." VALUES"; } $content .= "/n("; for($j=0; $j<$fields_amount; $j++) { $row[$j] = str_replace("/n","//n", addslashes($row[$j]) ); if (isset($row[$j])) { $content .= ''"''.$row[$j].''"'' ; } else { $content .= ''""''; } if ($j<($fields_amount-1)) { $content.= '',''; } } $content .=")"; //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) { $content .= ";"; } else { $content .= ","; } $st_counter=$st_counter+1; } } $content .="/n/n/n"; } //$backup_name = $backup_name ? $backup_name : $name."___(".date(''H-i-s'')."_".date(''d-m-Y'').")__rand".rand(1,11111111).".sql"; $backup_name = $backup_name ? $backup_name : $name.".sql"; header(''Content-Type: application/octet-stream''); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=/"".$backup_name."/""); echo $content; exit; } ?>


Prueba lo siguiente.

Ejecute una consulta de respaldo de la base de datos desde un archivo PHP. A continuación se muestra un ejemplo del uso de la consulta SELECT INTO OUTFILE para crear una copia de seguridad de tabla:

<?php $DB_HOST = "localhost"; $DB_USER = "xxx"; $DB_PASS = "xxx"; $DB_NAME = "xxx"; $con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME); if($con->connect_errno > 0) { die(''Connection failed ['' . $con->connect_error . '']''); } $tableName = ''yourtable''; $backupFile = ''backup/yourtable.sql''; $query = "SELECT * INTO OUTFILE ''$backupFile'' FROM $tableName"; $result = mysqli_query($con,$query); ?>

Para restaurar la copia de seguridad, solo necesita ejecutar la consulta LOAD DATA INFILE de esta manera:

<?php $DB_HOST = "localhost"; $DB_USER = "xxx"; $DB_PASS = "xxx"; $DB_NAME = "xxx"; $con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME); if($con->connect_errno > 0) { die(''Connection failed ['' . $con->connect_error . '']''); } $tableName = ''yourtable''; $backupFile = ''yourtable.sql''; $query = "LOAD DATA INFILE ''backupFile'' INTO TABLE $tableName"; $result = mysqli_query($con,$query); ?>


Puedes usar este comando o me funciona al 100%

exec(''C://wamp//bin//mysql//mysql5.6.17//bin//mysqldump.exe -uroot DatabaseName> c://database_backup.sql'');

Nota:
C://wamp//bin//mysql//mysql5.6.17//bin//mysqldump.exe es la ruta para la aplicación mysqldump, revisa tu pc.

-uroot es -u{UserName}

Si su base de datos está protegida con contraseña, agregue después de -uroot este sentense -p{YourPassword}


Si no tiene phpMyAdmin , puede escribir en los comandos de php CLI, como iniciar sesión en mysql y realizar db dump. En este caso, usaría la función shell_exec .


Sugeriría que hagas lo siguiente,

<?php function EXPORT_TABLES($host, $user, $pass, $name, $tables = false, $backup_name = false) { $mysqli = new mysqli($host, $user, $pass, $name); $mysqli->select_db($name); $mysqli->query("SET NAMES ''utf8''"); $queryTables = $mysqli->query(''SHOW TABLES''); while ($row = $queryTables->fetch_row()) { $target_tables[] = $row[0]; } if ($tables !== false) { $target_tables = array_intersect($target_tables, $tables); } $content = "SET SQL_MODE = /"NO_AUTO_VALUE_ON_ZERO/";/r/nSET time_zone = /"+00:00/";/r/n/r/n/r/n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;/r/n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;/r/n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;/r/n/*!40101 SET NAMES utf8 */;/r/n--Database: `" . $name . "`/r/n/r/n/r/n"; foreach ($target_tables as $table) { $result = $mysqli->query(''SELECT * FROM '' . $table); $fields_amount = $result->field_count; $rows_num = $mysqli->affected_rows; $res = $mysqli->query(''SHOW CREATE TABLE '' . $table); $TableMLine = $res->fetch_row(); $content .= "/n/n" . $TableMLine[1] . ";/n/n"; for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter = 0) { while ($row = $result->fetch_row()) { //when started (and every after 100 command cycle): if ($st_counter % 100 == 0 || $st_counter == 0) { $content .= "/nINSERT INTO " . $table . " VALUES"; } $content .= "/n("; for ($j = 0; $j < $fields_amount; $j++) { $row[$j] = str_replace("/n", "//n", addslashes($row[$j])); if (isset($row[$j])) { $content .= ''"'' . $row[$j] . ''"''; } else { $content .= ''""''; } if ($j < ($fields_amount - 1)) { $content.= '',''; } } $content .=")"; //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler if ((($st_counter + 1) % 100 == 0 && $st_counter != 0) || $st_counter + 1 == $rows_num) { $content .= ";"; } else { $content .= ","; } $st_counter = $st_counter + 1; } } $content .="/n/n/n"; } $content .= "/r/n/r/n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;/r/n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;/r/n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;"; $backup_name = $backup_name ? $backup_name : $name . "___(" . date(''H-i-s'') . "_" . date(''d-m-Y'') . ")__rand" . rand(1, 11111111) . ".sql"; header(''Content-Type: application/octet-stream''); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=/"" . $backup_name . "/""); echo $content; exit; } ?>

El proyecto enitre para exportación e importación se puede encontrar en https://github.com/tazotodua/useful-php-scripts .


Sugeriría que hagas lo siguiente,

<?php $con = mysqli_connect(''HostName'', ''UserName'', ''Password'', ''DatabaseName''); $tables = array(); $result = mysqli_query($con,"SHOW TABLES"); while ($row = mysqli_fetch_row($result)) { $tables[] = $row[0]; } $return = ''''; foreach ($tables as $table) { $result = mysqli_query($con, "SELECT * FROM ".$table); $num_fields = mysqli_num_fields($result); $return .= ''DROP TABLE ''.$table.'';''; $row2 = mysqli_fetch_row(mysqli_query($con, ''SHOW CREATE TABLE ''.$table)); $return .= "/n/n".$row2[1].";/n/n"; for ($i=0; $i < $num_fields; $i++) { while ($row = mysqli_fetch_row($result)) { $return .= ''INSERT INTO ''.$table.''VALUES(''; for ($j=0; $j < $num_fields; $j++) { $row[$j] = addslashes($row[$j]); if (isset($row[$j])) { $return .= ''"''.$row[$j].''"'';} else { $return .= ''""'';} if($j<$num_fields-1){ $return .= '',''; } } $return .= ");/n"; } } $return .= "/n/n/n"; } $handle = fopen(''backup.sql'', ''w+''); fwrite($handle, $return); fclose($handle); echo "success"; ?>


<?php $dbhost = ''localhost:3036''; $dbuser = ''root''; $dbpass = ''rootpassword''; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die(''Could not connect: '' . mysql_error()); } $table_name = "employee"; $backup_file = "/tmp/employee.sql"; $sql = "SELECT * INTO OUTFILE ''$backup_file'' FROM $table_name"; mysql_select_db(''test_db''); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die(''Could not take data backup: '' . mysql_error()); } echo "Backedup data successfully/n"; mysql_close($conn); ?>