Dump MySQL Database with PHP

A lightweight PHP approach to export MySQL databases without external tools.

Mon May 22 2023
— words · — minutes

Overview

A lightweight PHP approach to export MySQL databases without external tools.

Originally published on Jang Keyte's Blog.

This article covers Dump MySQL Database with PHP — practical notes from real-world web development experience.

Code Examples

/**
 * Cho phép hiển thị thông tin lỗi trong quá trình xử lý
 */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

/**
 * Tùy theo tài khoản đăng nhập mà sẽ load tất cả database được phân quyền
 */
$user = 'root';
$pass = '';
$host = 'localhost';

$db_backup_folder = "db_backup";
$dir = dirname(__FILE__);
/**
 * Kiểm tra thông tin cung cấp có kết nối được hay không
 */
$link = mysqli_connect($host, $user, $pass);
if (!$link) {
    die('Not connected : ' . mysql_error());
}

if (!$db_list = mysqli_query($link, "SHOW DATABASES"))
    printf("Error: %s\n", mysqli_error($link));
/**
 * Tiến hành lấy các database được phép truy cập
 */
$db_list_filtered = array();
$filter = array("information_schema", "mysql", "performance_schema");
while ($row = mysqli_fetch_row($db_list)) {
    if (!in_array($row[0], $filter)){
        $sql="SELECT table_schema 'db_name',
            SUM( data_length + index_length) / (1024 * 1024) 'db_size_in_mb'
            FROM information_schema.TABLES
            WHERE table_schema='$row[0]' GROUP BY table_schema ;";
        $query=mysqli_query($link, $sql);
        $data=mysqli_fetch_row($query);
        $db_list_filtered[$row[0]] = $data[1];
    }
}

Read More

For the full Vietnamese version, switch language using the VI | EN toggle above, or visit the original post.


Thanks for reading!

Dump MySQL Database with PHP

Mon May 22 2023
— words · — minutes