1

I need to export data (only the data, not the tables nor database) from the database to a SQL file and save it. How to write a PHP function that does that? I want to call this function in specific circumstances when running specific queries (updating a blog post, for example).

Something like:

/*
* Get the data from the database (already specified) and export it to a SQL file
*
* @param  string $dir Where to store the SQL file. Must be a full path.
* @return void
*/
function export_database_data(string $dir) {
  // some code that gets the data and store it in $data
  // don't know what to do here

  // create/update the file
  file_put_contents("$dir/data_backup.sql", $data);
}

Why this?

(You don't need to read the following to help me solve the problem. I'm including this because I'm sure if don't include this, someone will ask it).

I want to do that because I want to have a backup of the data (only the data; the tables do not matter because I already know how to handle them for backup).

I'm doing this because I will use the PHP function exec to run git commands and commit the change in the SQL file. The end goal is to keep track of the data in the database, which won't be updated often. I need the data in a SQL file and I aim to use git because it is easy to access and to collaborate with others (I could not think a better solution, and creating my own tracking system would require a lot of work and time).

ReynierPM
  • 15,161
  • 39
  • 158
  • 314

1 Answers1

3

You can run a mysqldump command using PHP exec function to only export data. Ex:

exec('mysqldump -u [user] -p[pass] --no-create-info mydb > mydb.sql');

More info:

ReynierPM
  • 15,161
  • 39
  • 158
  • 314