Make WordPress Core

Tagged: wpdb Toggle Comment Threads | Keyboard Shortcuts

  • Gary Pendergast 6:20 am on April 7, 2014 Permalink
    Tags: , , , , wpdb   

    MySQL in WordPress 3.9 

    In WordPress 3.9, we added an extra layer to WPDB, causing it to switch to using the mysqli PHP library, when using PHP 5.5 or higher.

    For plugin developers, this means that you absolutely shouldn’t be using PHP’s mysql_*() functions any more – you can use the equivalent WPDB functions instead.


    There are a few different options for replacing the query functions, depending on what you want to do:

    As a drop in replacement to run a query that you don’t expect a return value from (i.e., an INSERT, UPDATE or DELETE query), use $wpdb->query(). This will always return the number of rows effected by the query.

    Alternatively, $wpdb->insert(), $wpdb->update(), $wpdb->delete() and $wpdb->replace() are all helper functions that will automatically escape your data, then generate and run the queries for you. Ideally, you should never need to write an SQL statement!


    If you have a SELECT query, for which you’d normally do a mysql_query() followed by a mysql_fetch_*(), WPDB lets you combine this into one function call.

    To get all of the results from a query that returns more than one row, use $wpdb->get_results() to return an array of objects containing your data.

    There are also some shortcut functions for common usage:

    If you only need a single row from your query, $wpdb->get_row() will return just the data object from that row.

    If you only need a single column from a single row, $wpdb->get_var() will return only that field.

    And if you need a single column, $wpdb->get_col() will return an array of all the data from that column.


    For a drop in replacement, you can use esc_sql(). That said, we strongly recommend switching to $wpdb->prepare(), instead. We have a pretty thorough tutorial available for $wpdb->prepare().


    If you need to get the Insert ID from the last query, $wpdb->insert_id is where you need to look.

    Updating your plugin to use WPDB will also future proof it for if we make changes to how WordPress connects to the database – we’ll always maintain backwards compatibility with the current WPDB interface.

    For more reading, check the WPDB Codex page, and #21663.

    If you’re using MySQL in a way that I haven’t covered here, please post it in the comments, we’d be happy to help you out!

    • Samuel Wood (Otto) 6:23 am on April 7, 2014 Permalink | Log in to Reply

      Note: $wpdb->escape() is deprecated. Please use esc_sql() instead. Or $wpdb->prepare(), of course.

      Also note that $wpdb->escape() is not a proper replacement for mysql_real_escape_string() to begin with, as it only does weak escaping.

    • Doug Wollison 12:09 pm on April 7, 2014 Permalink | Log in to Reply

      I though I heard it was going to switch to PDO, not MySQLi?

      • Gary Pendergast 12:30 pm on April 7, 2014 Permalink | Log in to Reply

        That’s still on the cards for a future release, but it will be a significantly bigger project. The primary goal with this change was to stop using ext/mysql on PHP 5.5+, where it’s deprecated.

    • Brian Layman 4:10 pm on April 7, 2014 Permalink | Log in to Reply

      Wow! Huge change, and with the MySQL extension being deprecated in PHP 5.5 it’s a good one. I am trying to remember if 5.5 REQUIRES MySQLi to be built in. Does anyone know? Should you also throw in a check for the existence of mysqli_connect?

      Also, are there plans to start preparing queries? (Not WP prepare but the database meaning of prepare.)

      • Gary Pendergast 3:06 am on April 10, 2014 Permalink | Log in to Reply

        We do check that mysqli_connect() exists before trying to use it. (See wpdb::__construct().)

        There are no plans for adding statement prepare in the near future, though it is something I would like to get to!

    • webaware 10:46 pm on April 7, 2014 Permalink | Log in to Reply

      Plugin writers sometimes call mysql_get_server_info() to get the raw version information that $wpdb->db_version() strips out. Since the database handle isn’t public (nor is the mysqli indicator), there isn’t a way to do this in 3.9-beta3. I’ve opened a trac in hopes we can get a new method added to class wpdb so that plugin writers can still access this raw version information:


      • Gary Pendergast 5:28 am on April 8, 2014 Permalink | Log in to Reply

        To summarise the ticket, for anyone using mysql_get_server_info() – the best option is to have a switch in your code for mysqli, we’ll look at expanding $wpdb->db_version() at a later date.

        if ( empty( $wpdb->use_mysqli ) ) {
        	$ver = mysql_get_server_info();
        } else {
        	$ver = mysqli_get_server_info( $wpdb->dbh );
    • Claudio 8:51 pm on April 13, 2014 Permalink | Log in to Reply

      I use mysql_connect to test DB connectivity. How should I replace it for WP3.9/PHP5.5 compatibility?

      • Gary Pendergast 12:13 am on April 14, 2014 Permalink | Log in to Reply

        To test the connection, you can use $wpdb->check_connection(), which will check that the connection is up, and try to reconnect if it isn’t.

        This is particularly useful for long running cron jobs, where the MySQL connection might drop out due to inactivity, but there’s no actual problem with the server.

    • Ross Seddon 6:08 am on May 5, 2014 Permalink | Log in to Reply

      My web site which was designed using a standard off shelf theme I’m advised by our web site managers they site is providing the response “Access denied for user ‘www-data’@’localhost’ (using password: NO).” They advise
      Quote: “the one statement in there is exactly the issue: For plugin developers, this means that you absolutely shouldn’t be using PHP’s mysql_*() functions any more – you can use the equivalent WPDB functions instead.”

      The developer how wrote the plugin that is used site wide on your site for the skin, uses this no longer available method. All there work needs to be updated to use the correct method of connecting to the database. We know what is required, just that the plugin / skin is none of our work, and it is time consuming to fix.”

      We been down now for 3 weeks in terms of accessing site. Is what your referring to this thread relative to my site problem site http://www.totallyoutdoors.com.au

      how time consuming is this problem?


    • lwall 1:07 pm on May 15, 2014 Permalink | Log in to Reply

      I am having troubles with admin permissions at different points.

      When clicking on “Posts”, I get error “Invalid post type”, or when trying to create a new post, there is no save box/button.

      It also happens when trying to change options in one of my themes in other places with plugins. I get “You do not have sufficient permissions to access this page.”

      For the most part, the back-end is functional, the front-end is fully functional.

      I am using appengine 1.9.3 and wordpress 3.9, python 2.7.6.

      I have uninstalled 1.9.3 and updated to 1.9.4, I have also accepted WordPress’ request to install 3.9.1, the problem persists.

      I have installed the 1.9.3, 3.9, 2.7.6 configuration on a different machine where appengine was never installed before and the same problem occurs.

      I am discarding plugins because there were no plugins in the separate machine.

      I had appengine 1.9.0 and 1.9.3 working with WordPress 3.8.1. The problem started a few days ago after a number of upgrades (from 1.9.3 to 1.9.4, and into wordpress 3.9.1).

      Could this extra layer to WPDB be the source of this?

    • Michael Simpson 1:49 pm on July 11, 2014 Permalink | Log in to Reply

      For a plugin, I would like to be able to do unbuffered queries (MYSQLI_USE_RESULT). This is to handle cases when there are a lot of rows being returned and I want to keep the memory footprint down. wpdb doesn’t support this well and it would be nice if it would.

      For now, I have to create a new wpdb object and directly call mysqli_query($wpdb->dbh, $sql, MYSQLI_USE_RESULT); It is not using MySQLi, then I need to call mysql_unbuffered_query($sql, $wpdb->dbh);

      To know which one to call, I would like to consult $wpdb->use_mysqli but I cannot because it is private and there is no accessor method. So I have to copy the code from wp-db.php to determine it.

      For a start, it would be nice to be able to access $wpdb->use_mysqli. Even better would be an API on $wpdb to do unbuffered queries.


      • Gary Pendergast 2:02 pm on July 11, 2014 Permalink | Log in to Reply

        You can access $wpdb->use_mysqli directly, because of the wpdb::__get() magic getter.

        There’s unlikely to ever be an API in WPDB for doing unbuffered queries. There are too many gotchas that will just cause maintenance problems.

  • Andrew Nacin 6:14 am on December 12, 2012 Permalink
    Tags: , , sql, wpdb   

    PHP Warning: Missing argument 2 for wpdb::prepare() 

    Hello plugin or theme author! You possibly found this post after searching the Internet for the error above: “PHP Warning: Missing argument 2 for wpdb::prepare().”

    So, this is a new warning in 3.5. No sites are broken, everything is fine as before. But, this is indeed something you need to look at, because you may be exposing your users to a possible SQL injection vulnerability. Now that’s no fun!

    First, if you’re a user and you want to get rid of these errors, you should turn off the displaying of errors in PHP. There are many ways to do this, such as in php.ini, .htaccess, etc. For this, you can just put this in wp-config.php. (Note that hiding errors on production sites is good practice anyway.)

    <a href='https://profiles.wordpress.org/ini_set' class='mention'>@ini_set</a>('display_errors', 0);

    If you’re a user, you can stop here. (If you need more help, please don’t comment here, try the helpful Support Forums.) Just be sure to send a link to this post to the developer of the theme or plugin referenced in the error.

    Now, developers: Here’s how $wpdb->prepare() is supposed to work:

    $wpdb->prepare( "SELECT * FROM table WHERE ID = %d AND name = %s", $id, $name );

    See how $id — an integer, presumably — was passed as the second argument? That corresponds to the first placeholder, %d. Then, $name (a string) was passed as the third argument, thus the second placeholder, %s. This makes sure your query is safe, and prevents something like little bobby tables. (Note: the comic is wrong, don’t sanitize — always prepare your queries.)

    The problem is, a number of people were calling $wpdb->prepare() with only one argument, like so:

    $wpdb->prepare( "SELECT COUNT(*) FROM table" );

    See, there’s no parameter (%d, %s, or for floats, %f) in this query. This happens to work fine, but the prepare call isn’t doing anything. You should instead the query directly, as there are no inputs.

    But here’s where the problem lies:

    $wpdb->prepare( "SELECT * FROM table WHERE id = $id" );

    See the problem? That query isn’t secure! You may think you are “preparing” this query, but you’re not — you’re passing $id directly into the query, unprepared. And this, right here, is why $wpdb->prepare() now issues a warning if it isn’t called with more than one argument. Because you can’t prepare a query without more than one argument. Here’s a correct example:

    $wpdb->prepare( "SELECT * FROM table WHERE id = %d", $id );

    This wasn’t a decision done lightly. We don’t like shoving PHP warnings into the faces of users and developers. But given the potential security risks, we wanted everyone to immediately look at how they are running queries. And, of course, always prepare them properly.

    For more: wpdb Codex reference, #22262, and [22429].

    • Samuel Wood (Otto) 6:17 am on December 12, 2012 Permalink | Log in to Reply

      Dangit. Stole my ottopress post for tomorrow. Now I have to come up with fresh, original content. 😉

    • Emil Uzelac 6:23 am on December 12, 2012 Permalink | Log in to Reply

      Good one, just submitted this https://wordpress.org/support/topic/warning-missing-argument-2-for-wpdbprepare-3 15 minutes ago. Let me link to this post as well, to help author out :)


    • chacha102 6:30 am on December 12, 2012 Permalink | Log in to Reply

      Because you can’t prepare a query with more than one argument. Here’s a correct example:

      I think you mean, you can’t prepare a query without more than one argument.

    • Brian Layman 6:56 am on December 12, 2012 Permalink | Log in to Reply

      Interesting.. So the rule of “Always use prepare on queries” is simply wrong.
      It should be “Always use prepare on queries that built with variable arguments.”

      I’d always thought it did further sanitization of the query string itself, but I suppose that would be really hard to do without blocking some valid query people would inevitably want.

      • Samuel Wood (Otto) 6:58 am on December 12, 2012 Permalink | Log in to Reply

        The *vast* majority of problems with this I’ve seen today had variable arguments, but were putting them directly in the strings, like the third code example there. Which basically means that prepare did nothing to protect them.

        Previously, prepare(‘string’) returned ‘string’. Now it returns ‘string’ and a warning that you are doing-it-wrong. :)

      • chacha102 7:03 am on December 12, 2012 Permalink | Log in to Reply

        If you check out the source code for wpdb::prepare it really isn’t that interesting.

    • Vitor Carvalho 11:17 am on December 12, 2012 Permalink | Log in to Reply

      Fantastic explanation Nacin 😉

    • Joost de Valk 2:14 pm on December 12, 2012 Permalink | Log in to Reply

      Had to chuckle a bit when I found this:

      Missing argument 2 for wpdb::prepare(), called in /home/example/public_html/wp-content/plugins/akismet/admin.php

    • rfair404 2:14 pm on December 12, 2012 Permalink | Log in to Reply

      Thanks Nacin, I started seeing these notices in the last few weeks on several plugins that I use. glad to know what’s going on here.

    • a6april 3:18 pm on December 12, 2012 Permalink | Log in to Reply

      Thanks Huge Andrew, I had no idea! I am always glad to learn something everyday! I appreciate the quick followup and all of the responses. Have a great day all!

    • Josh 4:31 pm on December 12, 2012 Permalink | Log in to Reply

      Extremely useful… and “juicy”! Thanks Andrew! Saved me tons of time. Nice to know you guys are on top of security. Thanks again!

    • nomadentech 11:29 am on December 13, 2012 Permalink | Log in to Reply

      This is works perfectly, i think similar error will found in another plugins, so we dont need to fear for updating WordPress core. 😄
      Thank you,


    • properwp 6:01 pm on December 13, 2012 Permalink | Log in to Reply

      Thank you very much! We’re using a modified version of a clunky plugin in the repo and we keep finding new, wonderful problems. Another one of those “probably should have started from scratch” situations!

    • Mark de Scande BlogLines 8:04 pm on December 13, 2012 Permalink | Log in to Reply

      The only thing here is that it should have been noted some were or it was and i did not see it or i did not read i had the same problem on my Wife site SuperBlogs.co.za but on BlogLines.co.za it all was perfect on SB i just added some dirty code to make it go away


      But thx for posting it here for us all to see

    • Nashwan Doaqan 5:32 pm on December 14, 2012 Permalink | Log in to Reply

      Thank You Andrew Nacin , I see many plugins have this PHP warning .
      I hope a good life for all plugins authors 😄

    • DigiproveDevelopment 12:51 pm on December 15, 2012 Permalink | Log in to Reply

      Correction: some sites WERE broken because the warning messages screwed up the buffer and prevented normal operation.

      Am I the only one who thinks it was the wrong decision for WordPress team to decide that warnings will be spouted out for a situation where previously there was not even a Notice-level message? Like many authors I turn on notice-level messages when testing. And the underlying change caused so much difficulty because of a widespread but incorrect assumption that wpdb->prepare did actually do something with standalone sql strings when it fact what it did was – nothing.

      Suggest that:
      a) WordPress automatic upgrade process at least gives a warning to users who are using plugins not marked as being compatible with new release (e.g. like Firefox does).

      b) More use is made of notice-level messages fo situations like this so that sites don’t actually break when WordPress changes

      c) All registered plugin developers are warned by email of situations identified in beta testing which require action

compose new post
next post/next comment
previous post/previous comment
show/hide comments
go to top
go to login
show/hide help
shift + esc
Skip to toolbar