How to create a drop down list with database information?

Hi,

I’m trying to create a drop down list with information from a database-table in wordpress. Here is my function where I’m getting information from the table and creating a select-form.

function dd_ranalyzes_select(){

    global $wpdb;
    $table_name = $wpdb->prefix . 'table_name';
    $sql = "SELECT * FROM ". $table_name;

    $query_resource = mysql_query($sql);

    $select = '<select name="ranalyser" ';

    $select .= '><option value"">- Velg en -</option>';

    while ($ranalyse = mysql_fetch_assoc($query_resource)){
        
        $select .= '<option value='. $ranalyse['id'] .'>'. $ranalyse['name'] .'</option>';
    } 

    // close our select html tag
    $select .= '</select>';

    // return select
    return $select;
    }

But when I’m doing this, I’m getting this error:

Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given…

I have tried different stuff but nothing seems to work. Has somebody an idea how to fix this and can give me a hint?

Thanks for your help!

Get rid of the mysqli_ calls and replace them with either mysqli or PDO - the old interface was removed from PHP in December last year and now only works in dead versions of PHP.

Thanks for your help.

I have changed my code to this:

function dd_ranalyzes_select(){
      
    global $wpdb;
    $table_name = $wpdb->prefix . 'table_name';
    
    $select = '<select name="ranalyser">';

    $select .= '<option value"">- Velg en -</option>';
    
    $res = $wpdb->query("SELECT * FROM ". $table_name);
    
    while($row = $res->fetch_array()){
        
        $option = '<option value="'. $row->id .'">';
        $option .= $row->name;
        $option .= '</option>';
        
        // append our option to the select html
        $select .= $option;
    }
    
    // close our select html tag
    $select .= '</select>';
    
    // return select
    return $select;
}

But know im getting this error:

Fatal error: Call to a member function fetch_array() on integer…

I can’t figure out what I’m doing wrong.

That probably means the query is malformed. My guess would be the table name isn’t what you think it is.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.