Home  >  Article  >  Backend Development  >  How to Import a .sql File into a MySQL Database Using PHP: A Step-by-Step Guide?

How to Import a .sql File into a MySQL Database Using PHP: A Step-by-Step Guide?

Barbara Streisand
Barbara StreisandOriginal
2024-10-31 10:24:02335browse

How to Import a .sql File into a MySQL Database Using PHP: A Step-by-Step Guide?

How to Import a .sql File into a MySQL Database Using PHP

Importing a .sql file into a MySQL database using PHP can be easily accomplished, but requires careful attention to detail. Here's a detailed explanation:

Error Troubleshooting

Your error message indicates that the import file is not located in the same folder as your script. Ensure that the file path provided in the $mysqlImportFilename variable is correct and matches the location of your .sql file.

Alternative Approach

If you encounter issues with the exec() function, consider an alternative approach using the mysql_query() function as follows:

<code class="php"><?php

// Database connection details
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'test';

// Open connection
$conn = mysqli_connect($host, $user, $pass, $db);

// Read SQL file
$sql = file_get_contents('dbbackup.sql');

// Execute SQL queries
if (mysqli_multi_query($conn, $sql)) {
    echo 'Import file successfully imported.';
} else {
    echo 'Error importing file: ' . mysqli_error($conn);
}

// Close connection
mysqli_close($conn);

?></code>

Important Notes

  • The mysql_query() function is deprecated as of PHP 7.0.0, so it's recommended to use mysqli_query() or PDO instead.
  • When using the exec() function, ensure that the MySQL client is installed and accessible from the command line.
  • Make sure your database user has the necessary privileges to import the SQL file.

The above is the detailed content of How to Import a .sql File into a MySQL Database Using PHP: A Step-by-Step Guide?. 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