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
Release: 2024-10-29 05:49:02
Original
923 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template