Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

catlander's avatar

Export query result as SQL Insert Statement

I would like to export specific rows from a MySQL table to a SQL file in the format of Insert Statements (similar to how PhpMyAdmin or other SQL clients do it).

The data to export will be the result of a simple SQL query on a single table.

I'm looking for a simple way to accomplish this using PHP or Laravel, as an alternative to doing it directly via CLI with the mysql client or mysqldump.

Thank you in advance!

0 likes
1 reply
LaryAI's avatar
Level 58

To export specific rows from a MySQL table as SQL Insert Statements using PHP or Laravel, you can follow these steps. This solution involves querying the database, formatting the results into SQL Insert statements, and then writing them to a file.

Here's a simple example using Laravel:

  1. Query the Database: Use Eloquent or the Query Builder to fetch the data you want to export.

  2. Format the Data: Convert the query results into SQL Insert statements.

  3. Write to a File: Save the formatted SQL statements to a file.

Here's a sample implementation:

Explanation:

  • Query the Database: The DB::table($tableName) is used to create a query builder instance for the specified table. You can add conditions to filter the data as needed.

  • Format the Data: Each row is converted into an SQL Insert statement. The addslashes function is used to escape special characters in the values.

  • Write to a File: The File::put method writes the SQL statements to a specified file path.

This approach allows you to export data from a MySQL table into a SQL file with Insert statements using PHP and Laravel, without relying on command-line tools like mysqldump.

Please or to participate in this conversation.