[wp-trac] [WordPress Trac] #42352: Support use of native MySQLi prepared queries

WordPress Trac noreply at wordpress.org
Fri Oct 27 04:18:02 UTC 2017


#42352: Support use of native MySQLi prepared queries
-------------------------+------------------------------
 Reporter:  dd32         |       Owner:
     Type:  enhancement  |      Status:  new
 Priority:  normal       |   Milestone:  Awaiting Review
Component:  Database     |     Version:
 Severity:  normal       |  Resolution:
 Keywords:  early        |     Focuses:
-------------------------+------------------------------

Comment (by dd32):

 Specifically regarding [attachment:42352.diff], here's some very basic
 examples of how it can be used:
 {{{
 $post_id = 123;
 $var = $wpdb->get_var(
    "SELECT post_author FROM {$wpdb->posts} WHERE ID = ?",
    array( $post_id )
 );
 }}}

 Using numbered parameters isn't supported, and does require repeating the
 values in the args if that's something that's being done:
 {{{
 $user_search = "test-user";
 $user = $wpdb->get_row(
     "SELECT * FROM {$wpdb->users} WHERE user_login = ? OR user_nicename =
 ? OR user_email = ?",
     array(
         $user_search,
         $user_search,
         $user_search
    )
 );
 }}}

 Because prepared queries are only designed for being used with values, you
 can't use a placeholder for a table name (or fields), the following will
 NOT work (intentionally)
 {{{
 // does NOT work
 $wpdb->get_var(
    "SELECT ? FROM ? WHERE ? = ?",
    array( 'ID', $wpdb->users, 'user_login', 'admin' )
 );
 }}}

 If you need to be able to specify the type of a parameter, for example, as
 an integer or double that can be done by passing an array of data `type`
 and `value`:
 {{{
 $query = "SELECT * FROM {$wpdb->posts} WHERE post_author = ? OR post_name
 = ?";
 $args = array(
   // post_author:
    array(
      'type' => 'i', // integer
      'value' => 1,
    ),
    // post_name
    array(
      'type' => 's', // string
      'value' => 'my-post-name'
   )
 );

 $row = $wpdb->get_row( $query, $args );
 }}}

 The expanded syntax looks a bit verbose at first, but is only needed if
 you need to force an arg to either an integer (`i`) or a double/float
 (`d`), which may be useful for `INSERT/UPDATE` type queries. It can be
 mixed, using only arrays for integers/doubles and a direct string assumed
 as a string.

--
Ticket URL: <https://core.trac.wordpress.org/ticket/42352#comment:1>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list