"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Successfully Import .sql Files into MySQL Using PHP?

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

Published on 2024-11-12
Browse:497

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

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();
?>

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.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3