• Resolved patdundee

    (@patdundee)


    Hi Guys

    I have a function where, inside it I need to connect to a table and display results. The query woks fine outside of the function, but when i run it inside i get this error.

    Notice: Undefined variable: wpdb in /pathtopage/common.php on line 301 Fatal error: Call to a member function get_results() on a non-object in /path to page/common.php on line 301

    Here is the MySqlI query inside the function

    ` $options = array();
    $res= $wpdb->get_results (“SELECT County FROM counties”);
    $value=””;
    $label=”Please select a county”;
    $options[] = array(‘label’ => $label, ‘value’ => $value);
    foreach ($res as $row) {
    $sC=$row->ID;
    $res1=$wpdb->get_results (“select County from wedding_shows where County=’$sC'”);
    $res1_cnt->mysqli_num_rows($res1);
    if ($res1_cnt<1) {
    } else {
    $options[] = array(‘label’ => $row->County, ‘value’ => $row->ID);
    }
    }

    $dropdown = $form->getElement(‘iphorm_7_1’);
    if ($dropdown instanceof iPhorm_Element_Select) {
    $dropdown->setOptions($options);
    }
    }`

    Any ideas please
    Many thanks
    P

Viewing 2 replies - 1 through 2 (of 2 total)
  • When you’re running inside a function, that function doesn’t have any reference to the $wpdb object, as it was defined outside of that functions scope.

    To allow it to have reference you’d start off your function like this:

    function my_function() {
        global $wpdb;
    
        // Do everything here!
    }
    Thread Starter patdundee

    (@patdundee)

    Thank you once again 🙂

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘MySqli query inside a function’ is closed to new replies.