WordPress – Use one variable multiple times using $wpdb->prepare

Question

How do you use a variable multiple times when using $wpdb->prepare   ?

Answer

If you’re prepared SQL statement needs to refer to a variable more than once you need to include it multiple times.

For example, the SQL query below refers to the user_id twice – both for the use_id and conrtributor_use_id column

SELECT id, title, user_id, contributor_user_id WHERE user_id = 1 OR contributor_user_id = 1

To prepare this statement you would need to do this

$wpdb->prepare("SELECT id, title, user_id, contributor_user_id WHERE user_id = %d OR contributor_user_id = %d", $user_id, $user_id);