FrenchyNYC
FrenchyNYC

Reputation: 337

How to update database on load of a page?

I am on WORDPRESS and I would like to update the table called wppl_friends_locator and more precisely the fields lat and long of the logged in user

Each time the logged in visit the website, it actually grab his coordinates :

$latitude = ( !empty( $_COOKIE['gmw_lat'] ) ) ? urldecode( $_COOKIE['gmw_lat'] ) : false;
$longitude = ( !empty( $_COOKIE['gmw_lng'] ) ) ? urldecode( $_COOKIE['gmw_lng'] ) : false;

Now I would like that on certain pages, the database gets updated by these values when the user loads these pages...

What to do ? I am very new to PHP I try to understand, I know that I am not on a platform to ask and give the code but it takes me days to figure that kind of things so a little bit of help would be GREATLY appreciated !

Thanks !

Upvotes: 0

Views: 231

Answers (1)

litopj
litopj

Reputation: 116

put this in your themes functions.php

function update_coordinate( $latitude, $longitude ){
    global $current_user;
    global $wpdb;
    $update_result = false;

    if ( is_user_logged_in() ) {
        $update_arr = array(
            'latitude' => $latitude,
            'longitude' => $longitude
        );

        $update_result = $wpdb->update( 'wppl_friends_locator', $update_arr, array( 'user_id' => $current_user->ID ) );
    }

    return $update_result;
}

then call "update_coordinate" function (with latitude and longitude parameters) in your template file. You can call it after "get_footer()".

Here's a sample (i can't post a comment so i'll just add it here). You can also put it in your theme's footer.php after "wp_footer()"

$latitude = ( !empty( $_COOKIE['gmw_lat'] ) ) ? urldecode( $_COOKIE['gmw_lat'] ) : false;
$longitude = ( !empty( $_COOKIE['gmw_lng'] ) ) ? urldecode( $_COOKIE['gmw_lng'] ) : false;

update_coordinate( $latitude, $longitude );

UPDATE: Insert if current user has no row on the table

function update_coordinate( $latitude, $longitude ){
    global $current_user;
    global $wpdb;
    $query_result = false;

    if ( is_user_logged_in() ) {
        # check if user has record
        $row_count = $wpdb->get_var( $wpdb->prepare( 
            "SELECT count(member_id) FROM wppl_friends_locator WHERE member_id = %d", $current_user->ID ) );

        if ( $row_count > 0 ) {
            $update_arr = array(
                'lat' => $latitude,
                'long' => $longitude
            );
            $query_result = $wpdb->update( 'wppl_friends_locator', $update_arr, array( 'member_id' => $current_user->ID ) );

        }else{
            $insert_arr = array(
                'member_id' => $current_user->ID,
                'lat' => $latitude,
                'long' => $longitude
            );
            $query_result = $wpdb->insert( 'wppl_friends_locator', $insert_arr );

        }
    }   

    return $query_result;
}

Upvotes: 2

Related Questions