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).

6
  • 1
    Why not use mysqldump -u [user] -p[pass] --no-create-info mydb > mydb.sql? Check more here Commented Aug 23, 2019 at 19:51
  • ReynierPm Can I run this command with PHP exec function? Is "mydb" the name of the database? Commented Aug 23, 2019 at 19:53
  • Fantastic! I'll try it out! You should post it as the answer! Commented Aug 23, 2019 at 19:54
  • 1
    Pretty sure one of those tags doesn't belong there. Commented Aug 23, 2019 at 19:54
  • 1
    Much better. dev.mysql.com/doc/refman/8.0/en/mysqldump.html Commented Aug 23, 2019 at 19:55

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

3 Comments

I'll try and let you know how that goes
I ran your code and, altough I got no error, it did not create the file. Can you help me again? Where I can post my code (here in the comments or on the post) ?
I figured out what I was doing wrong and your command worked !! Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.