Best Practices: Importing a MySQL File with PHP and Splitting Queries
When updating a website hosted on a shared server with a CMS, one may encounter the need to import a large database file using PHP. In such cases, it is crucial to split the file into individual queries for reliable execution.
A proven solution for this task is the SplitSQL function, which efficiently splits the file without requiring the entire file to be loaded into memory. The function takes a file path and an optional query delimiter as input.
Inside the function, a loop iterates over the file line by line. Each line is added to an array that gradually builds up a query. When the array contains a complete query terminated by the delimiter, it is executed using mysql_query().
After executing each query, the output is flushed and the query array is reset. The process continues until the end of the file is reached.
To test the SplitSQL function, you can use a sample SQL dump. Executing the function on this data will produce successful query execution messages for each statement in the dump.
By leveraging the SplitSQL function, you can confidently import large database files into your PHP scripts, ensuring that queries are executed reliably and efficiently.
The above is the detailed content of How to Efficiently Import Large MySQL Files with PHP and Split Queries?. For more information, please follow other related articles on the PHP Chinese website!