13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Backing Up Your <strong>MySQL</strong> Database<br />

305<br />

Using Indexes<br />

You should use indexes where required to speed up your queries. Keep them simple <strong>and</strong><br />

don’t create indexes that are not being used by your queries.You can check which<br />

indexes are being used by running EXPLAIN, as shown previously.<br />

Using Default Values<br />

Wherever possible, you should use default values for columns <strong>and</strong> insert data only if it<br />

differs from the default.This way, you reduce the time taken to execute the INSERT statement.<br />

Other Tips<br />

You can make many other minor tweaks to improve performance in particular situations<br />

<strong>and</strong> address particular needs.The <strong>MySQL</strong> website offers a good set of additional tips.You<br />

can find it at http://www.mysql.com.<br />

Backing Up Your <strong>MySQL</strong> Database<br />

In <strong>MySQL</strong>, there are several ways to do a backup.The first way is to lock the tables<br />

while you copy the physical files, using a LOCK TABLES comm<strong>and</strong> with the following<br />

syntax:<br />

LOCK TABLES table lock_type [, table lock_type ...]<br />

Each table should be the name of a table, <strong>and</strong> the lock type should be either READ or<br />

WRITE. For a backup, you only need a read lock.You need to execute a FLUSH TABLES;<br />

comm<strong>and</strong> to make sure any changes to your indexes have been written to disk before<br />

performing a backup.<br />

Users <strong>and</strong> scripts can still run read-only queries while you make your backup. If you<br />

have a reasonable volume of queries that alter the database, such as customer orders, this<br />

solution is not practical.<br />

The second, <strong>and</strong> superior, method is using the mysql_dump comm<strong>and</strong>. Usage is from<br />

the operating system comm<strong>and</strong> line, <strong>and</strong> is typically something such as<br />

mysqldump --opt --all-databases > all.sql<br />

This comm<strong>and</strong> dumps a set of all the SQL required to reconstruct the database to the<br />

file called all.sql.<br />

You should then stop the mysqld process for a moment <strong>and</strong> restart it with the<br />

--log-bin[=logfile] option.The updates stored in the log file give you the changes<br />

made since your dump. (Obviously, you should back up the log files in any normal file<br />

backup.)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!