There is a much easier way of locking all tables, but it entails 'abusing' the FLUSH command to lock all tables. Flushing your entire database means MySQL will reload its various internal caches, so this may not play well with large tables/databases.
I have only tried this with MyISAM tables, and I have heard people say this doesn't work properly for InnoDB tables, so be careful if your table type is not MyISAM.
Here's how to do it:
mysql_query("FLUSH TABLES WITH READ LOCK");
/* do stuff while entire database is locked */
mysql_query("UNLOCK TABLES");
If you use MySQL replication you can avoid syncing the FLUSH command to the slave server by changing the first query to:
mysql_query("FLUSH LOCAL TABLES WITH READ LOCK");