Yesterday I looked at how to copy a table with MySQL using some SQL queries. This post looks at how to automate the process with a PHP script saving you having to type in and adjust queries each time you want to back up a table.
The script below connects to a MySQL database server on "localhost" using the login name "test" and password "123456" and then connects to the database "test". It then copies the table structure and data from the table "products" to a new table "products_bak". If the target table already exists the function returns false.
The table_exists() function comes from an earlier post on this blog titled PHP function to check if a MySQL table existsand published in June 2008. Read that post for more information about that particular function.
Note that there is no error checking after the calls to mysql_query so you'd want to add this in yourself and/or change the mysql_* calls to use whatever database abstraction library you use in your own projects.
Note also that the copy_table() function could also call table_exists() on the $from table as well to make sure that exists too, in order to prevent errors in the query calls.
To copy multiple tables you can either call the copy_table function multiple times, or put the to and from tablenames into an associative array and loop through them like so:
In Thursday's PHP post I'll look at how to enhance this script to run it from the command line passing the from and to table names from the command line, and will also add in error checking.
0 comments:
Post a Comment