如何使用php代码或在codeigniter中以.sql扩展名导出mysql数据库

问题描述 投票:0回答:3

如何使用 php 代码或 codeigniter 代码下载 .sql 文件!

php mysql codeigniter export
3个回答
5
投票
$this->dbutil->backup()

允许您备份完整数据库或单个表。备份数据可以压缩为 Zip 或 Gzip 格式。

注意:此功能仅适用于 MySQL 数据库。 注意:由于 PHP 的执行时间和可用内存有限,可能无法备份非常大的数据库。如果您的数据库非常大,您可能需要通过命令行直接从 SQL 服务器备份,或者如果您没有 root 权限,请让您的服务器管理员为您执行此操作。

使用示例

// Load the DB utility class
$this->load->dbutil();

// Backup your entire database and assign it to a variable


$backup =& $this->dbutil->backup(); 

// Load the file helper and write the file to your server

$this->load->helper('file');

write_file('/path/to/mybackup.sql', $backup); 

// Load the download helper and send the file to your desktop

$this->load->helper('download');

force_download('mybackup.sql', $backup);

点击链接


2
投票

这里是下载数据库备份的完整 PHP 代码

<?php

// Database configuration
$host = "localhost";
$username = "db-username";
$password = "db-password";
$database_name = "db-name";

// Get connection object and set the charset
$conn = mysqli_connect($host, $username, $password, $database_name);
$conn->set_charset("utf8");


// Get All Table Names From the Database
$tables = array();
$sql = "SHOW TABLES";
$result = mysqli_query($conn, $sql);

while ($row = mysqli_fetch_row($result)) {
    $tables[] = $row[0];
}

$sqlScript = "";
foreach ($tables as $table) {
    
    // Prepare SQLscript for creating table structure
    $query = "SHOW CREATE TABLE $table";
    $result = mysqli_query($conn, $query);
    $row = mysqli_fetch_row($result);
    
    $sqlScript .= "\n\n" . $row[1] . ";\n\n";
    
    
    $query = "SELECT * FROM $table";
    $result = mysqli_query($conn, $query);
    
    $columnCount = mysqli_num_fields($result);
    
    // Prepare SQLscript for dumping data for each table
    for ($i = 0; $i < $columnCount; $i ++) {
        while ($row = mysqli_fetch_row($result)) {
            $sqlScript .= "INSERT INTO $table VALUES(";
            for ($j = 0; $j < $columnCount; $j ++) {
                $row[$j] = $row[$j];
                
                if (isset($row[$j])) {
                    $sqlScript .= '"' . $row[$j] . '"';
                } else {
                    $sqlScript .= '""';
                }
                if ($j < ($columnCount - 1)) {
                    $sqlScript .= ',';
                }
            }
            $sqlScript .= ");\n";
        }
    }
    
    $sqlScript .= "\n"; 
}

if(!empty($sqlScript))
{
    // Save the SQL script to a backup file
    $backup_file_name = $database_name . '_backup_' . time() . '.sql';
    $fileHandler = fopen($backup_file_name, 'w+');
    $number_of_lines = fwrite($fileHandler, $sqlScript);
    fclose($fileHandler); 

    // Download the SQL backup file to the browser
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($backup_file_name));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($backup_file_name));
    ob_clean();
    flush();
    readfile($backup_file_name);
    exec('rm ' . $backup_file_name); 
}
?>

参考:https://phppot.com/php/how-to-backup-mysql-database-using-php/


0
投票
function upload()
{
    $file = $this->request->getFile('csv');
    if ($file->isValid() && !$file->hasMoved()) {
        $imagename = $file->getRandomName();
        $file->move('uploads/', $imagename);
    }
    $files = fopen("uploads/" . $imagename, "r");

    $i = 0;
    $numberOfFields = 8;

    $csvArr = array();

    while (($filedata = fgetcsv($files, 1000, ",")) !== FALSE) {
        $num = count($filedata);


        if ($i > 0 && $num == $numberOfFields) {
            $csvArr[$i]['file_id'] = $filedata[0];
            $csvArr[$i]['brand'] = $filedata[1];
            $csvArr[$i]['model'] = $filedata[2];
            $csvArr[$i]['year'] = $filedata[3];
            $csvArr[$i]['color'] = $filedata[4];
            $csvArr[$i]['mileage'] = $filedata[5];
            $csvArr[$i]['price'] = $filedata[6];
            $csvArr[$i]['conditions'] = $filedata[7];
        }
        $i++;
    }

    fclose($files);


    $count = 0;
    foreach ($csvArr as $userdata) {
        $model = new UserModel();

        // Check record
        $checkrecord = $model->where('file_id', $userdata['file_id'])->countAllResults();

        if ($checkrecord == 0) {

            ## Insert Record
            if ($model->insert($userdata)) {
                $count++;
            }
        }
    }
    return "data insert successfull";
}


function success()
{
    $filename = "car_details_data_in_ci4-" . date('ymd') . ".csv";
    $fields = array('file_id', 'brand', 'model', 'year', 'color', 'mileage', 'price', 'conditions');
    $excelData = implode(",", array_values($fields)) . "\n";
    $model = new UserModel();
    $fetch = $model->findAll();
    if (!empty($fetch)) {
        $i = 0;
        foreach ($fetch as $row) {
            $i++;
            $rowdata = [
                $i,
                $row['brand'],
                $row['model'],
                $row['year'],
                $row['color'],
                $row['mileage'],
                $row['price'],
                $row['conditions']
            ];

            $excelData .= implode(",", array_values($rowdata)) . "\n";
        }
    } else {
        $excelData .= 'no record founds ...' . "\n";
    }
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Type: application/force-download");
    echo $excelData;
    exit;
}
© www.soinside.com 2019 - 2024. All rights reserved.