Mysqli Query In WordPress

Wonder if you can help me figure this out. Latest PHP in WordPress 3.92. WordPress is using MySqli. I am trying to change my custom MYSQL to MYSQLI which should really be simple enough, but is throwing up so issues.

Below are 2 examples. Example 1 is using WordPress built in MYSQLI connection inside a function and the one underneath is my own. The first one throws up errors as shown but my own one does not.

Read More
function name{
global $wpdb;
$options = array();
$res=mysqli_query($wpdb,"select ID,County from counties ORDER BY County ASC");
$value="";
$label="Please select a county";
$options[] = array('label' => $label, 'value' => $value);
    while($row=mysqli_fetch_array($res)) {
    $sC=$row['ID'];
    $res1=mysqli_query($wpdb,"select County from wedding_shows where County='$sC'");
        if (mysqli_num_rows($res1) == 0) {
        } else {
        $options[] = array('label' => $row['County'], 'value' => $row['ID']);
        }
    }
}

Here are the errors i get

Warning: mysqli_query() expects parameter 1 to be mysqli, object given eval()’d code on line 3

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given eval()’d code on line 4

and here is it working with my own connection and no errors.

function name(
$dbhost1 = 'localhost';
$dbuser1 = 'user';
$dbpass1 = 'pass';
$dbname1 = 'DBName';
$conn=mysqli_connect($dbhost1 ,$dbuser1,$dbpass1,$dbname1);
$options = array();
$res=mysqli_query($conn,"select ID,County from counties ORDER BY County ASC");
$value="";
$label="Please select a county";
$options[] = array('label' => $label, 'value' => $value);
    while($row=mysqli_fetch_array($res)) {
    $sC=$row['ID'];
    $res1=mysqli_query($conn,"select County from wedding_shows where County='$sC'");
        if (mysqli_num_rows($res1) == 0) {
        } else {
        $options[] = array('label' => $row['County'], 'value' => $row['ID']);
        }
             }
}

I must be looking to hard as I cannot see why this would not work in the first instance to save having to create a new connection inside every function.

Many thanks
P

Related posts

Leave a Reply

1 comment

  1. The first argument of mysqli_query is expected to be a mysqli connection object. $wpdb is not a mysqli connection object, it is the wordpress database object. That being said, you could just do $wpdb->get_results("select ID,County from counties ORDER BY County ASC"); instead, given that the query is proper.