On $wpdb->prepare

If you do the following, you’re a terrible person:

$query = "SELECT ID from {$wpdb->posts} WHERE ID = %d";
$query = $wpdb->prepare( $query, $value );

There is absolutely no reason for prepare to be on a separate line.

Here’s how you do it the right way:

$query = $wpdb->prepare( "SELECT ID from {$wpdb->posts} WHERE ID = %d", $value );

One line. Simple, easy to read, and not confusing.

4 thoughts on “On $wpdb->prepare

  1. You know how they come to that anti-pattern though, right? They want to isolate the query, so that if it was more easily cowboy coded — add and remove print and debug.

    Wonder if prepare() having a debug/echo parameter would be useful, or too abstract… aside, does WP still not have as good of debug infrastructure as bbPress?

    • The problem is that prepare doesn’t do much other than sprintf the query with the values passed in. Developers can still do something like:

      $query = $wpdb->prepare( "SELECT ID from {$wpdb->posts} WHERE ID = %d", $value );
      error_log( 'Woo! I'm querying IDs! My query: ' . $query );
      $id = $wpdb->get_col( $query );

      Which is why this anti-pattern baffles me…

Comments are closed.