Home >Database >Mysql Tutorial >How to Successfully Import a .SQL File into MySQL Using PHP?

How to Successfully Import a .SQL File into MySQL Using PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-31 15:55:13380browse

How to Successfully Import a .SQL File into MySQL Using PHP?

How to Import a .SQL File in MySQL Database Using PHP

When attempting to import a .SQL file into a MySQL database through PHP, you may encounter an error stating, "There was an error during import. Please make sure the import file is saved in the same folder as this script and check your values." To resolve this issue and successfully import the file, follow the steps outlined below:

The error message suggests that the problem lies in the PHP code you provided. Here's an alternative approach using the mysqli extension instead of the deprecated mysql_* functions:

<?php

// Name of the file
$filename = 'churc.sql';

// MySQL host
$mysql_host = 'localhost';

// MySQL username
$mysql_username = 'root';

// MySQL password
$mysql_password = '';

// Database name
$mysql_database = 'dump';

// Connect to MySQL server
$mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database);

// Check connection
if ($mysqli->connect_error) {
    die('Error connecting to MySQL server: ' . $mysqli->connect_error);
}

// Read in entire file
$lines = file($filename);

// Loop through each line
foreach ($lines as $line) {
    // Skip it if it's a comment
    if (substr($line, 0, 2) == '--' || $line == '') {
        continue;
    }

    // Execute the query
    if ($mysqli->query($line) === false) {
        echo 'Error performing query \'<strong>' . $line . '\': ' . $mysqli->error . '<br /><br />';
    }
}

 echo "Tables imported successfully";

$mysqli->close();
?>

This code establishes a connection to the MySQL server using the mysqli extension. It then reads the contents of the .SQL file line by line and executes each line as a query. The mysqli->error property is used to handle any errors that may occur during query execution.

Remember to ensure that the .SQL file is located in the same directory as your PHP script, and that the database name, username, password, and host address specified in the code are correct.

The above is the detailed content of How to Successfully Import a .SQL File into MySQL Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn