Smashing Magazine - we smash you with the information that will make your life easier. really.

8 Useful WordPress SQL Hacks

Advertisement

By Jean-Baptiste Jung

Over the past 10 years, the MySQL database has become incredibly popular on the Web. Every WordPress blog is driven by a MySQL database, which contains the blog’s posts, settings, comments and much more.

While plug-ins and even coding hacks can solve some problems and achieve some tasks, sometimes you don’t have any other choice than to execute SQL commands in phpMyAdmin or directly to the database via SSH. Let’s take a look at 8 useful SQL hacks for WordPress. Each section of this post presents a problem, suggests a solution and provides an explanation to help you understand the solution.

1. Creating a Backup of Your Database

Sm5 in 8 Useful WordPress SQL Hacks

The problem. While the tips in the rest of this post have been tested, you should definitely not try any of them without first having a proper backup of your MySQL database.

The solution. To create a manual backup of your WordPress database, follow these simple steps:

  1. Log in to phpMyAdmin and select your WordPress database.
  2. Once done, click the “Export” button located in the horizontal menu.
  3. Choose a compression method (personally, I use gzip), and click the “Execute” button.
  4. Your browser will ask you if you want to download the backup. Of course, select “Yes,” and then store it on your hard drive.

Explanation. Note that creating a backup of your WordPress database can be more easily executed with the WP-DB-Backup plug-in. WordPress users should install this plug-in if they have not yet done so and create regular backups of their data.

2. Batch Delete Post Revisions

Sm1 in 8 Useful WordPress SQL Hacks

The problem. Post revisions, a new WordPress 2.6 feature, can be very useful, but they also increase the size of your MySQL database. Sure, you can manually delete posts revisions, but that’s very long and boring work.

The solution. The solution to this problem is simple: we batch delete post revisions by using a simple SQL query. The result can be almost unbelievable if you have a lot of posts: Your database size will be reduced by half!

  1. Log in to phpMyAdmin and select your WordPress database.
  2. Click the “SQL” button. Paste the following code in the SQL command window:
    DELETE FROM wp_posts WHERE post_type = "revision";
  3. You’re done. Depending on how many posts you had in your WordPress database, you may have saved lots of precious space!

Code explanation. The wp_posts table has a field named post_type. This field can have one of many values, such as “post,” “page” or “revision.” When we want to get rid of post revisions, we simply run a command to delete any entry in the wp_posts table in which the post_type field is equal to “revision.”

Source:

3. Erase 5000 Spam Comments in a Second

Sm3 in 8 Useful WordPress SQL Hacks

The problem. True story: a friend of mine recently created his own blog and started to promote it everywhere on the Internet. After some weeks of intensive work, he spent some days on vacation without Internet access.

When he came back home, he looked at his blog and saw… 5000+ comments awaiting moderation! Of course, most of them were spam, but he was actually about to check them all to make sure he did not delete a valid comment made by one of his regular readers.

The solution. Happily, my friend told me about his spam problem. He had already spent 45 minute manually deleting spam when I showed him this useful SQL tip.

  1. Log in to phpMyAdmin and select your WordPress database.
  2. Click the “SQL” button. Paste the following code in the SQL command window:
    DELETE from wp_comments WHERE comment_approved = '0';
  3. Goodbye bad comments! Enjoy your spam-free database!

Explanation. The wp_comments table contains a field named comment_approved, which is a boolean value (1 or 0). Approved comments have a value of 1, and comments awaiting moderation have a value of 0. By running the above command, we simply delete any comments that haven’t been approved yet.

Be careful. While this solution can be pretty useful if you have millions of spam comments to delete, it will also erase valid unapproved comments. If you don’t already use Akismet, install it now to prevent spamming.

Source:

4. Change the Post Attribution

Sm4 in 8 Useful WordPress SQL Hacks

The problem. When you installed WordPress, an “admin” account was created. Some bloggers make the mistake of using that account to write their posts, until they realize that it’s not personal at all.

The solution. Modifying author attribution on each post takes a lot of time. Happily, SQL can help you get things done:

  1. Log in to your phpMyAdmin and select your WordPress database.
  2. First, we have to get the right user IDs. To do so, open the SQL command window and execute the following command:
    SELECT ID, display_name FROM wp_users;
  3. phpMyAdmin will display a list of user IDs associated with WordPress users. Let’s say that NEW_AUTHOR_ID is the ID of the more recently created author, and OLD_AUTHOR_ID is the original admin account ID.
  4. After you swap the NEW_AUTHOR_ID and OLD_AUTHOR_ID IDs, run the following command:
    UPDATE wp_posts SET post_author=NEW_AUTHOR_ID WHERE post_author=OLD_AUTHOR_ID;
  5. That’s all. All posts previously attributed to admin are now attributed to whichever valid user you have selected.

Source:

5. Manually Reset Your Password

Sm6 in 8 Useful WordPress SQL Hacks

The problem. In order to protect their blogs, people often pick strong passwords, such as u7*KoF5i8_. Of course, this is a good thing, but I have heard many stories of forgotten admin passwords.

The solution. When you lose your password, WordPress can email you a link to reset it. But if you don’t have access to the email address recorded in the WordPress database anymore, or if you prefer just running a simple command instead, here is the hack.

  1. Log in to your phpMyAdmin, select your WordPress database and open the SQL window.
  2. Insert the following command (assuming your username is “admin”):
    UPDATE `wp_users` SET `user_pass` = MD5('PASSWORD') WHERE `wp_users`.`user_login` =`admin` LIMIT 1;
  3. You’re done. Your password has been successfully replaced by whatever you inserted in space above marked “PASSWORD.”

Explanation. User passwords are stored in the wp_users table. Of course, an MD5 hash is used to secure the password.

We have to set up an “UPDATE” SQL request and use the built-in MD5() MySQL function to convert our password to MD5 and then update it. The “WHERE” clause ensures that we’re updating only the admin’s password. The same request without the “WHERE” clause would result in all passwords being updated!

Source:

6. Change Your WordPress Domain Name

Sm7 in 8 Useful WordPress SQL Hacks

The problem. Although it is not recommended, you may want at some point to change your domain name while keeping your blog and its data. Because WordPress records your domain name in the database, you have to change the database in order to connect your new domain name to your WordPress blog.

The solution.

  1. You guessed it: the first thing to do is log in to your phpMyAdmin and select your WordPress database.
  2. Click the “SQL” button to open the SQL command window. In order to change your WordPress URL, execute this first command:
    UPDATE wp_options SET option_value = replace(option_value, 'http://www.oldsite.com', 'http://www.newsite.com') WHERE option_name = 'home' OR option_name = 'siteurl';
  3. Then, we have to replace the relative URL (guid) of each post. The following command will do that job:
    UPDATE wp_posts SET guid = replace(guid, 'http://www.oldsite.com','http://www.newsite.com');
  4. We’re almost done. The last thing to do is a search and replace in the wp_posts table to make sure that no absolute URL is still here:
    UPDATE wp_posts SET post_content = replace(post_content, 'http://www.oldsite.com', 'http://www.newsite.com');
  5. You’re done. You should be able to log in to your WordPress dashboard using your new URL.

Explanation. To easily change our WordPress domain name, I took advantage of the super-useful MySQL function “replace,” which allows you to replace one term by another.

Source:

7. Display the Number of SQL Queries on Your blog

Sm8 in 8 Useful WordPress SQL Hacks

The problem. When trying to optimize your blog’s loading time, knowing the number of queries made to the database is important. In order to reduce queries, the first thing to know is how many queries are made on a single page.

The solution.

  1. This time, no need to log in to phpMyAdmin. Simply open the footer.php file in your theme and append the following lines of code:
    <?php if (is_user_logged_in()) { ?>
        <?php echo get_num_queries(); ?> queries in <?php timer_stop(1); ?> seconds.
    <?php } ?>
  2. Save the file and visit your blog. In the footer, you’ll see the number of queries made to the WordPress database as well as the time it took to make them.

Explanation. Seems that many WordPress users aren’t aware of this useful function. The get_num_queries() function returns the number of executed queries during a page load.

Note that the above code will only display the number of queries to logged-in users, because regular visitors and search engine bots don’t need to know about it. But, if you’d like to make it public, simply remove the if (is_user_logged_in()) conditional instruction.

Source:

8. Restore Your WordPress Database

Sm9 in 8 Useful WordPress SQL Hacks

The problem. Let’s say, for some reason, such as a hacking or upgrade problem, you have lost your blog data or it has become corrupted. If you have a backup (and I hope you do!) you will have to import it to your WordPress database.

The solution.

  1. Log in to phpMyAdmin and select your WordPress database.
  2. Click the “Import” button in the horizontal menu.
  3. Click the “Browse” button and select the most recent database backup on your hard disk.
  4. Click the “Execute” button. If everything went well, your WordPress database is fully functional again.

(al)

This guest post was written by Jean-Baptiste Jung, a 26-year-old blogger from Belgium, who blogs about WordPress at WpRecipes and about everything related to blogging and programming at Cats Who Code. You can stay in touch with Jean by following him on Twitter.

Post Rating
1 Star2 Stars3 Stars4 Stars5 Stars (No votes yet)
Loading ... Loading ...

Tags: , ,

Advertising
  1. 1
    Lee Rickler
    December 18th, 2008 3:46 pm

    Number 1 can also be done automatically as a cron job with the file emailed to you at a set time.

  2. 2
    progressiveOne
    December 18th, 2008 3:54 pm

    Nice and useful tips (especially the DB ones). Thanks for sharing!

  3. 3
    Christopher LCP Mendes
    December 18th, 2008 3:56 pm

    The Search and Replace plugin can do most of this in a user-friendly way: http://wordpress.org/extend/plugins/search-and-replace/

    I recommend it, but be sure to use WP-Backup (mentioned in the article) before hand.

  4. 4
    Damien
    December 18th, 2008 4:02 pm

    Ahem if the wordpress database is a big big (more than 2Mo usually. It depends of the php.ini configuration), the phpmyadmin importer won’t work because the file won’t be uploaded.

    The best solution is and stays the mysql one, not the phpmyadmin one.
    Generate the backup : http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html
    And to get it back, in a shell, enter the following :
    mysql -u [username] -p [password] [database_to_restore] < [backupfile]

    It requires a shell access but it’ll be working on any database, big or smaller (and the bigger are usually much more painfull with phpmyadmin than smaller ones).

  5. 5
    Anrkist
    December 18th, 2008 6:26 pm

    Wow, those are exceptional! I could have used the Password hack today without bugging my boss to reset the password.

    Going to try the Spam hack tommorow… We have about 500 comments in spam.

    Are these WP Version specific? I upgraded to 2.7 yesterday.

  6. 6
    Joe W.
    December 18th, 2008 6:28 pm

    I love the post BTW.

    What I need is to do is change the /Dir/ for uploaded images listed in posts inside the SQL data base. I have posted in the wordpress forums and recived not one peep of help.

  7. 7
    Jeff O'Hara
    December 18th, 2008 6:33 pm

    Just a tip, to backup a database from the command line, do “mysqldump -u username -p databasename > databasename.sql

  8. 8
    Jeff O'Hara
    December 18th, 2008 6:35 pm

    restoring a database would be “mysqldump -u username -p databasename < databasename.sql”

  9. 9
    Jay
    December 18th, 2008 7:01 pm

    @Damien
    Most of the hosting provider doesn’t give you shell access. So, it’s a good idea to stick to phpmyadmin whenever it’s possible.
    One trick that I do to overcome this limitation is to enable built in phpmyadmin Webserver upload/save/import directories (by editing config.inc.php file of phpmyadmin). Search for this string: $cfg['SaveDir'] and enter a directory in your web server. Next time you do any exporting, you have new option to save it to server directory, then later you can download it using F TP.

  10. 10
    Matt Fox
    December 18th, 2008 8:22 pm

    Nice tips. The most useful thing I’ve ever done to my Wordpress installations is to install and update them with Subversion- it’s an absolute lifesaver. Now I don’t worry when they release a new version, because it take me 20 seconds to log into my server and run “svn sw”… That would be a good follow-up post topic.

  11. 11
    Ansell Cruz
    December 18th, 2008 8:47 pm

    Im not sure if it is md5 hash for the password. As you can see the characters generated contains characters such as * _ ^ $ and all. MD5 only contains 0-9 and A-F, or the so called hex code. correct me if Im wrong though

  12. 12
    Hans Petter
    December 19th, 2008 12:37 am

    A lot of good tips here, e.g. the one to recover the password. But some of these tips can also be done by using the Wordpress admin section, e.g. changing the name shown when using the administrator-account

  13. 13
    aniec2
    December 19th, 2008 12:53 am

    very interesting art. ty bro.

  14. 14
    dani
    December 19th, 2008 12:54 am

    good post really…thanx :)
    P.S something similar should be done for joomla

  15. 15
    Volly
    December 19th, 2008 12:59 am

    Nice article.
    An appendix for point 2:
    You can easy configure how many post revisions will be saved.
    Just insert the following code into your wp_config.php
    define('WP_POST_REVISIONS', 3);

    Explanation: WP_POST_REVISIONS specifies how many revisions will be stored in database (0=no revisions saved)

    see: article in wordpress codex

  16. 16
    Andy Guilder
    December 19th, 2008 12:59 am

    I agree with Dani – A joomla version would be great :) thanks for this!

  17. 17
    Rainbow
    December 19th, 2008 1:35 am

    Beau travail JBJ ! Continue ainsi !

  18. 18
    Srednarb
    December 19th, 2008 1:43 am

    I love the hack that uses mysql command, that make wordpress make easier specially if you have access on shell :)

  19. 19
    John J
    December 19th, 2008 2:54 am

    # 7 is a handy one indeed. I,m using it sinds I use the WP admin.

  20. 20
    Luciano Passuello
    December 19th, 2008 3:00 am

    The “Batch Delete Post Revisions” doesn’t delete the associated metadata with post revisions.
    To make sure you delete the post revision WITH all related data, use the following command:


    DELETE a,b,c
    FROM wp_posts a
    LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
    LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)
    WHERE a.post_type = 'revision'

    (code stolen from Lester Chan).

  21. 21
    oneighturbo.com
    December 19th, 2008 5:27 am

    Thanks for the these! Will use in the future!

  22. 22
    DKumar M.
    December 19th, 2008 5:57 am

    Thanks for good set of tips….keep up the good work !!

    DKumar M.
    http://www.instantshift.com

  23. 23
    nevermind
    December 19th, 2008 6:07 am

    don’t try to jump on programmers turf SM. just be the designer. last time a designer tried to touch a db, he just dropped all the tables “by mistake”

  24. 24
    Andy H
    December 19th, 2008 6:24 am

    It’s perfectly true that any SQL dump over about 2Mb will be difficult to import. I had a 24Mb database and phpMyAdmin choked on it repeatedly.The solution was a very cool php script called (amusingly) BigDump (http://www.ozerov.de/bigdump.php) which enables you to upload the entire db archive file via FTP and then BigDump will incrementaly import it into your mySQL database. This is extremely useful as you do not require any shell access as some other solutions require. :)

  25. 25
    Chris
    December 19th, 2008 6:38 am

    ^^ Typical of elitist programmers. There’s a lot of designers out there becoming web developers via WP. It’s a great way to learn PHP and MySQL.

    Great post by the way. A lot of good tips for WP/MySQL n00bs like myself.

  26. 26
    hey
    December 19th, 2008 6:39 am

    What is the WordPress? I can use it for internet?

  27. 27
    rpsms
    December 19th, 2008 7:32 am

    The mysql manual an be found at:

    http://www.mysql.com/

    I don’t think the article suitably warns sql newbies of the dangers of execute queries. There is NO UNDO feature, and yes, you can totally hose an entire database with a few words.

    while someone labeled it “elitist”, #23’s post (above) is a valid warning. I’ve personally witnessed drop table incidents.

  28. 28
    LowLevelIndian
    December 19th, 2008 8:58 am

    I really wouldn’t call these “hacks,” more like workarounds. Love the idea though. What about doing a list of real hacks? Like adding custom, multiple TinyMCE fields in the page and post editor, or hacks extending the CMS functionality of the wordpress core.

  29. 29
    Chris Laing
    December 19th, 2008 1:46 pm

    I agree with Ansell Cruz Password recovery method didn’t work for me. I found village-idiot dot org who provide emergency password recovery that worked fine.

  30. 30
    Mark
    December 19th, 2008 2:33 pm

    Instead of using phpmyadmin with it’s PHP limits on file sizes, just download the MySQL client. It works awesome, and you can open an entire local .sql script and execute. For a database software, it has a very nice interface, and even includes an easy to use manual for creating and executing your own queries.

    Dear Elitest Programmer,
    Why are you reading a design blog? Last time I saw a design from a programmer, I barfed in my mouth a little because of all the solid gray tones. That was sarcasm if you didn’t get it.

  31. 31
    Chris M.
    December 19th, 2008 7:31 pm

    Pretty good stuff.
    To change the domain of a wordpress site, I just use the search feature in phpMyAdmin. I search the old url (all the tables), it will return two queries in the wp_options table. Edit and replace both with the new URL. Works for me.

  32. 32
    akumasign
    December 19th, 2008 8:16 pm

    Thanks for the these! nice data.

  33. 33
    Jhay
    December 20th, 2008 4:37 am

    Nice post! Very useful

  34. 34
    Srecko Bradic
    December 20th, 2008 4:39 am

    Great article! Keep on good work!

    Cheers

  35. 35
    Željan
    December 20th, 2008 6:06 am

    Most of this tips are bad, especially the one with deleting spam comments! The only two that could be applicable is tutorial on how to restore and backup DB. Author should better highlight the importance of messing with DB, especially with ‘delete’ and ‘update’ syntax!!!

  36. 36
    dalidas
    December 20th, 2008 2:46 pm

    It’s very nice that you ive writing the subjects about seo. (WP)
    Esperially it is nice as visual.

  37. 37
    Sunshine
    December 20th, 2008 5:58 pm

    Great info!

  38. 38
    hamdan
    December 20th, 2008 7:37 pm

    Thank you so much for the tips, especially the URL moving one.
    :)

  39. 39
    Anthony
    December 21st, 2008 9:42 am

    I’m definitely gonna refer back to this post next time one of these problems pop up B-)

  40. 40
    Frank
    December 21st, 2008 10:36 am

    I wrote a little one-line script to backup my WP database to a different partition using mysqldump and run it as a cron job every morning in the wee hours.

    Anyone who’s interested can read about it here

  41. 41
    Frank
    December 21st, 2008 10:57 am

    Oh, yeah, I then embedded the command in a longer script which creates a folder named with today’s date and sends the *.sql file into that folder. The longer script is the cron job.

  42. 42
    Kyle Potts
    December 21st, 2008 11:08 am

    Number 1 and 8 I most recently had to use, Upgrading to wordpress 2.7 causes problems, but luckily i remembered to backup my database before i upgraded.

  43. 43
    Glenn Haggard
    December 22nd, 2008 10:31 am

    Great tips! I’m sure I’ll be using them. The easiest way that I’ve found to reset a Wordpress password is to create a user with the password that you want and then just copy the password from that user to the user that you’re trying to reset. For example, the MD5 hash for “password” is “$P$Bq8Zk0hCxoUDcKV8jcmymS1Q10dQbz0″. Password reset.
    I really like the easy method of bulk deleting post revisions. Very nice! I hope I never have to change the domain name of an existing WP install.

  44. 44
    Sueblimely
    December 22nd, 2008 11:56 am

    I wish I had known about no.6 when I transferred a test site to its correct domain name. I ended up doing a lot of manual editing. I am now going to reduce my own database hopefully dramatically by ridding it of post revisions. Thank you for these tips and the clear directions.

  45. 45
    John
    December 24th, 2008 6:50 am

    I have a question in regards to #6.

    What if you’re wanting to switch from one web host to another and also change your blog’s address from my-site.com/blog to my-site.com?

    Would #6 still apply or do I have to do something else?
    Thanks

  46. 46
    Boo
    December 27th, 2008 8:52 am

    These are not `hacks’ — they’re just simple SQL queries (with little thought necessary to come up with them). And most of this stuff can be done from within the WordPress Dashboard.

  47. 47
    DG
    December 29th, 2008 5:06 pm

    THANK YOU! You just saved me a lot of misery on 4 different blogs over-run with Spam by posting #3.

  48. 48
    Aw Guo
    January 9th, 2009 8:44 pm

    Great tips :) really valuable!

  49. 49
    alastair
    January 28th, 2009 6:46 am

    Thankyou, amazingly helpful.

  50. 50
    Kerry Webster
    February 20th, 2009 10:29 pm

    @Luciano Passuello – #20 – Used this SQL just now. Backed up the DB before hand (4.5MB), ran the SQL, backed up afterwards (3.0MB). Saving space already. Good find and update to the original post. Thanks.

  51. 51
    Tommy
    February 28th, 2009 7:31 am

    Thanks for the tips! It really help a lots in my blog :D

  52. 52
    Coheed
    March 25th, 2009 7:12 am

    Is the password tip (these aren’t hacks) relevant anymore? I know WP added a salt to the password at some point — straight MD5 hashes aren’t that safe because of rainbow tables — so I don’t think this tip will actually work.

  53. 53
    Aaron
    April 15th, 2009 9:50 am

    Very useful thanks for the good article as always

  54. 54
    Scott Kingsley Clark
    April 17th, 2009 6:25 am

    on #6, you can really screw up cforms by doing this, so I’d suggest adding this extra WHERE statement:

    option_name NOT LIKE ‘%cforms%’

  55. 55
    Rory Hart
    September 7th, 2009 4:52 pm

    Thanks #6 saved me heaps of time that I would have had to spend probably installing phpmyadmin! Tagging in delicious for future reference! :D

    Rory
    What is the Science

  1. 00

    There are no trackbacks at this time. If you are interested in leaving a trackback, please use this URL.

Leave a Comment

Make sure you enter the * required information where indicated. Please also rate the article as it will help us decide future content and posts. Comments are moderated – and rel="nofollow" is in use. Please no link dropping, no keywords or domains as names; do not spam, and do not advertise!



Advertisement Advertise with us!
Join in Smashing Forum
  • Re: Correct way to learn PHP

    Start off by reading all the 15 parts of PHP 101 on Devzone.

  • Re: Using Tutorials?

    I say you're okay. I wouldn't straight up jack someone else's design and present it as my own, even if it was a tutorial, but it's certainly acceptable to learn some…

  • Correct way to learn PHP

    So, I'm a designer but I wanna expand my abilities and learn PHP, to be more exact I wanna learn CI - Codeigniter!

  • I wanna make comics!

    Hello,I'm designer but I've never involved in vector painting so I need your help

  • Re: Twitter

    @gatorwebdesignShould tweet something really...

Post your job