Support » Fixing WordPress » Help with custom SQL queries $wpdb->get_results()

  • I am trying to write some custom SQL queries into my WordPress templates, and then immediately iterate through the records and display them on the page (e.g. like a list of categories).

    I came across the ‘$wpdb->get_results()’ syntax, which works perfectly fine for a simply query, e.g:

    $wpdb->get_results("SELECT * FROM wp_posts WHERE field = 21");

    However what I need to do next is to pass a value into the SQL query. Is this possible with the ‘get_results’ function?

    I was hoping to do this as follows, but this does not work and I assume is not supported in the ‘get_results’ function:

    $wpdb->get_results("SELECT * FROM wp_posts WHERE field= %d", 21)

    Is this possible? And if not, is there an alternative which will work? Cheers.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Why don’t you use this?
    `$feild_var = 21;
    $wpdb->get_results(“SELECT * FROM wp_posts WHERE field= “. $feild_var);

    I was thinking about that but havent actually tried it.

    I avoided that method because I assumed it was prone to SQL injections. Unless I can wrap the value in something to prevent this?

    I’m not much experienced. Can you please, refer me to some study you’ve found on this topic (SQL Injection from …) Sorry 🙁

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Help with custom SQL queries $wpdb->get_results()’ is closed to new replies.