How to find and replace text in a MySQL database

There are a few posts on this blog about the Facebox jQuery plugin, and as I discovered this morning the website URL for the plugin has changed so I needed to update all links to it. The quickest way to do this was to update the MySQL database directly using UPDATE and REPLACE to find the old URLs and replace them with the new URLs. So here’s how to find and replace text in a MySQL database.

MySQL connections and PHP forked processes

It is possible to fork a process with PHP and have one or more child processes running. If a connection has already been established to a MySQL database and the child processes run queries it’s quite likely a "MySQL server has gone away" or a "Lost connection to MySQL server during query" type error will occur.

MySQL “Incorrect key file for table” error

When saving a record to a MySQL table the other day I got the error message “Incorrect key file for table ‘mytable’; try to repair it”. I am uncertain why the error occured and how to ensure it doesn’t happen again in the future but a quick fix for the time being is simple.

How to repair a MySQL table

All you need to do is to repair the table by running the following SQL command, where “mytable” is the name of the table that gave the error:

REPAIR TABLE `mytable`;
 

You can run this from e.g. the MySQL CLI or phpMyAdmin. From phpMyAdmin select the table, then “Operations” from the navigation tabs in the right frame above the table info; then “Repair Table” from the “Table maintenance” options at the bottom of the page.

When the table is /tmp/#sql_xxx_x.MYI

If the error looks like “Incorrect key file for table ‘/tmp/#sql_xxx_x.MYI’; try to repair it” where it refers to a temporary location on the filesystem, it’s likely you’ve run out of diskspace. Read my follow up post for more information.

PHP script to export table creation SQL from MySQL

I was trying to export the structure of a MySQL database using phpMyAdmin but it kept timing out and not showing me the full create script. I think phpMyAdmin uses the information schema to get this information and its on a host with hundreds of databases and tables so querying the information schema runs very slowly. Instead I knocked together a quick PHP script to dump the structure instead and share it here.