WordPress.org

Ready to get started?Download WordPress

Forums

Help with custom SQL queries $wpdb->get_results() (4 posts)

  1. DG55tom
    Member
    Posted 1 year ago #

    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.

  2. LIMEXS
    Member
    Posted 1 year ago #

    Why don't you use this?
    `$feild_var = 21;
    $wpdb->get_results("SELECT * FROM wp_posts WHERE field= ". $feild_var);

  3. DG55tom
    Member
    Posted 1 year ago #

    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?

  4. LIMEXS
    Member
    Posted 1 year ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.