I have a sql query that I use to populate a table with data. It looks like this


   $client = $wpdb->get_results("SELECT concat (string, string2), type FROM `file` WHERE `code` = incoming AND `status` = new");

 $header = array("concat", "type");

  echo "<thead><tr>";
  foreach ($header as $list) {
          echo '<th >' . $list . '</th>';
        echo "<thead></tr>";
  foreach ($client as $key => $value) {
    $counter = 0;
    foreach ( $value as $a ) {

              $url = get_template_directory_uri();

              if ($counter == 0) {
                echo '<td><a href="'.$url.'/mywebsiteurl/' . $a . '">'. htmlspecialchars($a) .' </a></td>';
              } else {
                echo '<td>'. htmlspecialchars($a) .'</td>';
            echo '</tr>';

Now after adding search filters, I have realized that maybe it would be better if I use a prepared statement. I have tried rewriting my query following WP codex but I get errors. I've been trying with prepare().

How do I do this and will I be able to extract the data in a foreach loop using the prepared statement?

  • What errors did you get? What does your try with prepare() look like? Also, note that $wpdb->prepare() isn't working with what is commonly understood as prepared statements in databases. It returns simple SQL that is safe to execute with $wbpb->query(), $wpdb->get_var() etc.
    – janh
    Commented Oct 9, 2017 at 15:35
  • I wasn't aware of that. So if I have $wpdb->prepare() I would still need to use $wpdb->get_results and then pass them in a foreach loop? What would be the purpose of doing it then? I'll edit the OP with the errors I get shortly
    – R1ddler
    Commented Oct 10, 2017 at 12:27
  • The main point is that you don't have to worry about escaping data when you use ->prepare with printf-like placeholders, e.g. ->prepare("... meta_key = %s", $meta_key). Using it helps you protect yourself against SQL-injections.
    – janh
    Commented Oct 10, 2017 at 12:37


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.