Hướng dẫn how can i connect sql file in php? - làm cách nào để kết nối tệp sql trong php?

Trong các dự án của tôi, tôi đã sử dụng giải pháp tiếp theo:

<?php

/**
 * Import SQL from file
 *
 * @param string path to sql file
 */
function sqlImport($file)
{

    $delimiter = ';';
    $file = fopen($file, 'r');
    $isFirstRow = true;
    $isMultiLineComment = false;
    $sql = '';

    while (!feof($file)) {

        $row = fgets($file);

        // remove BOM for utf-8 encoded file
        if ($isFirstRow) {
            $row = preg_replace('/^\x{EF}\x{BB}\x{BF}/', '', $row);
            $isFirstRow = false;
        }

        // 1. ignore empty string and comment row
        if (trim($row) == '' || preg_match('/^\s*(#|--\s)/sUi', $row)) {
            continue;
        }

        // 2. clear comments
        $row = trim(clearSQL($row, $isMultiLineComment));

        // 3. parse delimiter row
        if (preg_match('/^DELIMITER\s+[^ ]+/sUi', $row)) {
            $delimiter = preg_replace('/^DELIMITER\s+([^ ]+)$/sUi', '$1', $row);
            continue;
        }

        // 4. separate sql queries by delimiter
        $offset = 0;
        while (strpos($row, $delimiter, $offset) !== false) {
            $delimiterOffset = strpos($row, $delimiter, $offset);
            if (isQuoted($delimiterOffset, $row)) {
                $offset = $delimiterOffset + strlen($delimiter);
            } else {
                $sql = trim($sql . ' ' . trim(substr($row, 0, $delimiterOffset)));
                query($sql);

                $row = substr($row, $delimiterOffset + strlen($delimiter));
                $offset = 0;
                $sql = '';
            }
        }
        $sql = trim($sql . ' ' . $row);
    }
    if (strlen($sql) > 0) {
        query($row);
    }

    fclose($file);
}

/**
 * Remove comments from sql
 *
 * @param string sql
 * @param boolean is multicomment line
 * @return string
 */
function clearSQL($sql, &$isMultiComment)
{
    if ($isMultiComment) {
        if (preg_match('#\*/#sUi', $sql)) {
            $sql = preg_replace('#^.*\*/\s*#sUi', '', $sql);
            $isMultiComment = false;
        } else {
            $sql = '';
        }
        if(trim($sql) == ''){
            return $sql;
        }
    }

    $offset = 0;
    while (preg_match('{--\s|#|/\*[^!]}sUi', $sql, $matched, PREG_OFFSET_CAPTURE, $offset)) {
        list($comment, $foundOn) = $matched[0];
        if (isQuoted($foundOn, $sql)) {
            $offset = $foundOn + strlen($comment);
        } else {
            if (substr($comment, 0, 2) == '/*') {
                $closedOn = strpos($sql, '*/', $foundOn);
                if ($closedOn !== false) {
                    $sql = substr($sql, 0, $foundOn) . substr($sql, $closedOn + 2);
                } else {
                    $sql = substr($sql, 0, $foundOn);
                    $isMultiComment = true;
                }
            } else {
                $sql = substr($sql, 0, $foundOn);
                break;
            }
        }
    }
    return $sql;
}

/**
 * Check if "offset" position is quoted
 *
 * @param int $offset
 * @param string $text
 * @return boolean
 */
function isQuoted($offset, $text)
{
    if ($offset > strlen($text))
        $offset = strlen($text);

    $isQuoted = false;
    for ($i = 0; $i < $offset; $i++) {
        if ($text[$i] == "'")
            $isQuoted = !$isQuoted;
        if ($text[$i] == "\\" && $isQuoted)
            $i++;
    }
    return $isQuoted;
}

function query($sql)
{
    global $mysqli;
    //echo '#<strong>SQL CODE TO RUN:</strong><br>' . htmlspecialchars($sql) . ';<br><br>';
    if (!$query = $mysqli->query($sql)) {
        throw new Exception("Cannot execute request to the database {$sql}: " . $mysqli->error);
    }
}

set_time_limit(0);

$mysqli = new mysqli('localhost', 'root', '', 'test');
$mysqli->set_charset("utf8");

header('Content-Type: text/html;charset=utf-8');
sqlImport('import.sql');

echo "Peak MB: ", memory_get_peak_usage(true)/1024/1024;

Trên Tệp kiểm tra SQL (41MB) Sử dụng đỉnh bộ nhớ: 3,25MB

bởi Vincy. Sửa đổi lần cuối vào ngày 9 tháng 7 năm 2022.

Nhập tập lệnh SQL thông qua lập trình sẽ hữu ích khi chúng ta cần tạo cấu trúc cơ sở dữ liệu một cách linh hoạt. Ví dụ: nếu chúng tôi & nbsp; cung cấp ứng dụng hoặc plugin để tải xuống và & nbsp; cài đặt trực tuyến, nhập SQL Dynamic sẽ được sử dụng để thiết lập cơ sở dữ liệu ứng dụng tại thời điểm cài đặt ứng dụng hoặc plugin.

Trong hướng dẫn này, chúng tôi sẽ nhập tệp SQL vào cơ sở dữ liệu bằng cách sử dụng lập trình PHP. Trong ví dụ này, chúng tôi có một tệp chứa SQL để tạo bảng liên hệ & nbsp; và chèn dữ liệu. Mã PHP phân tích từng dòng tệp theo từng dòng và trích xuất các câu lệnh truy vấn đến & nbsp; thực thi bằng hàm php mysql.

Mã PHP đến & nbsp; nhập sql

Mã PHP đơn giản này được sử dụng để nhập tệp SQL vào cơ sở dữ liệu. Nó trích xuất nội dung tệp vào một mảng các dòng bằng cách sử dụng tệp PHP (). Mảng dòng được lặp lại trong một vòng lặp foreach để xây dựng truy vấn bằng cách bỏ qua & nbsp; nhận xét và các dòng trống.

Hướng dẫn how can i connect sql file in php? - làm cách nào để kết nối tệp sql trong php?

Điều kiện kiểm tra xem dòng có chứa các ký hiệu được sử dụng làm dấu phân cách dòng bình luận như ( -, /*, //). Nếu vậy, vòng lặp bỏ qua lần lặp hiện tại và tiếp tục với lần lặp tiếp theo.

Theo cách này, nó lặp lại giống nhau cho đến khi kết thúc câu lệnh truy vấn. Một lần, phần cuối của ký tự truy vấn được tìm thấy sau đó truy vấn sẽ được thực thi. Sau đó, biến truy vấn sẽ được đặt lại trước khi bắt đầu lặp lại tiếp theo.

<?php
$conn =new mysqli('localhost', 'root', '' , 'blog_samples');

$query = '';
$sqlScript = file('database-script.sql');
foreach ($sqlScript as $line)	{
	
	$startWith = substr(trim($line), 0 ,2);
	$endWith = substr(trim($line), -1 ,1);
	
	if (empty($line) || $startWith == '--' || $startWith == '/*' || $startWith == '//') {
		continue;
	}
		
	$query = $query . $line;
	if ($endWith == ';') {
		mysqli_query($conn,$query) or die('<div class="error-response sql-import-response">Problem in executing the SQL query <b>' . $query. '</b></div>');
		$query= '';		
	}
}
echo '<div class="success-response sql-import-response">SQL file imported successfully</div>';
?>

Tải xuống

Trở lại đầu