Does $wpdb->prepare not create a prepared statement that I can execute multiple times?

$wpdb-prepare works like sprintf and vsprintf. The first argument will always be a format string.

The only acceptable format specifiers are %s and %d. Others I have never tested but may result in parse error as per the Codex. You must escape literal % in your query with %, e.g: %%

If you use it like sprintf which is only possible if you know the number of arguments before runtime then you can the number of arguments should match the number of format specifiers in your format string.

E.g: $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}_votes WHERE post_id = %d AND username = %s", $post_id, $username );

If you don’t know the number of arguments till the runtime then you must use it like vsprintf. In this case the first argument will be format specifier but the second argument will be an array.

E.g: $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}_votes WHERE post_id = %d AND username = %s", array( $post_id, $username ) );

$wpdb->prepare will return a SQL QUERY string which you can execute as many times as you like.

For the above examples the resulted query will be: SELECT * FROM wp_votes WHERE post_id = 747 AND username="cooluser"

Leave a Comment