How to correctly execute a database query

Hi all!
I Can’t figure out mysqli_query
There is such old code that suits me, but does not work with PHP 7.2:

global $wpdb, $table_prefix;

$prefix = $wpdb->get_blog_prefix();

define( 'TABLE_USERS', $prefix .'users' );
define( 'TABLE_USER_ONLINE', $prefix .'users_session' );

function update_user_online() {
    global $user_id;
    wp_get_current_user();

    $user_id           = '';
    $full_name       = 'User';
    $session           = session_id();
    $ip                    = getenv( 'REMOTE_ADDR' );
    $last_page_url  = getenv( 'REQUEST_URI' );
    $current_time   = time();
    $mins_ago        = $current_time - 300;

    // <---- Warning: mysqli_query() expects at least 2 parameters, 1 given
    mysqli_query("delete from " . TABLE_USER_ONLINE . " where time_last_click < '" . $mins_ago . "'");

    // <---- Warning: mysqli_query() expects at least 2 parameters, 1 given
    $stored_user_query = mysqli_query( "select count(*) as count from ". TABLE_USER_ONLINE ." where session_id = '". esc_sql( $session ) ."'" );

    // <----- Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given
    $stored_user = mysqli_fetch_array( $stored_user_query );

    if ( $stored_user['count'] > 0 ) {
        // <---- Warning: mysqli_query() expects at least 2 parameters, 1 given in
        mysqli_query( "update ". TABLE_USER_ONLINE ." set user_id = '". (int)$user_id ."', full_name = '". esc_sql( $full_name ) ."', ip_address = '". esc_sql( $ip ) . "', time_last = '". esc_sql( $current_time ) ."', last_page_url = '". esc_sql( $last_page_url ) ."' where session_id = '". esc_sql( $session ) ."'");
    } else {
        // <----- mysqli_query() expects at least 2 parameters, 1 given
        mysqli_query( "insert into ". TABLE_USER_ONLINE ." (user_id, full_name, session_id, ip_address, time_entry, time_last, last_page_url) values ( '". (int)$user_id ."', '". esc_sql( $full_name ) ."', '". esc_sql( $session ) ."', '". esc_sql( $ip ) ."', '". esc_sql( $current_time ) ."', '". esc_sql( $current_time ) ."', '" . esc_sql( $last_page_url ) ."' )" );
    }
}

As far as I could, I fixed the errors but cannot figure out mysqli_query and mysqli_fetch_array
Help on the shelves to fix errors, maybe you need to use $ wpdb instead

You cant just throw an i on the end of old mysql_* code. The manual is quite clear on the format of procedural Mysqli and the need to pass the connection parameter. There are numerous examples right on the manual page.

mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] ) : mixed

1 Like