Home >Backend Development >PHP Tutorial >How to Successfully Import .sql Files into MySQL Using PHP?

How to Successfully Import .sql Files into MySQL Using PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 05:49:02907browse

How to Successfully Import .sql Files into MySQL Using PHP?

Importing .sql Files into MySQL Using PHP

When attempting to import a .sql file through PHP, an error may arise, indicating that the import file is not in the same folder as the script or that the values are incorrect.

Determining the Issue

The provided code executes a command using the exec() function to import the .sql file. However, the error message suggests that the import file cannot be found or that the values for the database connection are incorrect.

Alternative Approach

Rather than using the exec() function, a more reliable method is to use the MySQLi extension, which provides explicit support for MySQL database interactions in PHP.

Revised Code

<code class="php"><?php
// Name of the SQL file to import
$filename = 'dbbackupmember.sql';

// MySQL connection credentials
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'test';

// Create a new MySQLi connection
$mysqli = new mysqli($hostname, $username, $password, $database);
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
    exit;
}

// Get the contents of the SQL file
$sql = file_get_contents($filename);

// Execute the SQL statements
$result = $mysqli->multi_query($sql);

// Check the execution status
if ($result) {
    echo "SQL file imported successfully.";
} else {
    echo "Error importing SQL file: " . $mysqli->error;
}

// Close the connection
$mysqli->close();
?></code>

In this code:

  • A new MySQLi connection is created using the provided credentials.
  • The contents of the .sql file are read into the $sql variable.
  • The multi_query() function is used to execute all the SQL statements in the file one by one.
  • The status of the execution is checked, and an appropriate message is displayed.

The above is the detailed content of How to Successfully Import .sql Files 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