title: When should I use $wpdb->prepare, if at all?
body: <p>I have a hard time figuring out if I should be using <code>$wpdb-&gt;prepare</code> on my database queries in WordPress to prevent things such as SQL injection.</p>
  
  <p>The <a href="https://codex.wordpress.org/Class_Reference/wpdb" rel="nofollow noreferrer" title="Codex">$wpdb Codex</a> shows some examples using the $wpdb->prepare function, and other examples not using it.</p>
  
  <p>Also, in <a href="https://stackoverflow.com/a/16040644/849987" title="this answer">this answer</a> on StackOverflow, someone mentioned that a function such as <code>$wpdb-&gt;insert</code> has the same level of safety as using <code>$wpdb-&gt;prepare</code>. But what about other <code>$wpdb</code> functions such as <code>$wpdb-&gt;get_var</code> or <code>$wpdb-&gt;query</code>?</p>
  
  <p><strong>When should I use <code>$wpdb-&gt;prepare</code>, if at all?</strong></p>
  
  <p>Some of my (simplified) <code>$wpdb</code> class and function usage looks like this:</p>
  
  <hr>
  
  <p><strong>Example 1:</strong> <code>$wpdb-&gt;insert</code></p>
  
  <pre><code>$wpdb-&gt;insert(
                  'special_posts', 
                      array( 
                          'title' =&gt; $title,
                          'selftext_html' =&gt; $selftext_html,
                          'selftext' =&gt; $selftext,
                      ), 
  
                      array(
                          '%s',
                          '%s',
                          '%s',
                      )
              );
  </code></pre>
  
  <hr>
  
  <p><strong>Example 2:</strong> <code>$wpdb-&gt;get_results</code></p>
  
  <pre><code>$wpdb-&gt;get_results("SELECT * FROM special_posts WHERE selftext_html = '$value'");
  </code></pre>
  
  <hr>
  
  <p><strong>Example 3:</strong> <code>$wpdb-&gt;get_var</code></p>
  
  <pre><code>$wpdb-&gt;get_var("SELECT title FROM special_posts ORDER BY id DESC LIMIT 1");
  </code></pre>
  
  <hr>
  
  <p><strong>Example 4:</strong> <code>$wpdb-&gt;query</code></p>
  
  <pre><code>$wpdb-&gt;query('TRUNCATE TABLE special_posts');
  </code></pre>