1

Here is my PHP function:

function getUserIDandPush($ul){
    global $table_prefix; // Prefix for Database table
    global $user_login;
    global $wpdb; // Wordpress WPDB database method 
    $dt = $table_prefix; //Tables Prefix
    $as = $wpdb->get_results('SELECT * FROM '.$dt.'users WHERE user_login = "'.$ul.'" ');
    $usID = $as[0]->ID;
    wp_set_current_user($usID, $ul);
    wp_set_auth_cookie($usID);
    do_action('wp_login', $ul);
}

The issue is that $as[0]->ID returns Undefined offset: 0,

I'm not sure why is this returning that. The function works and does exactly what I want. But, why this error occurs?

Seeking some learning..

  • $ul is not defined, and you should really read about securing database requests. :) – fuxia Apr 19 '16 at 17:59
  • Its an intranet site. Not to worried as its only accessible from our computers. But I see your point. – Cam Apr 19 '16 at 18:01
  • This is all being done via ldap – Cam Apr 19 '16 at 18:03
  • If you are getting this data from the wordpress users table, you should take a look at get_user_by, one of the options is get by login developer.wordpress.org/reference/functions/get_user_by – czerspalace Apr 19 '16 at 19:51
0

Fixed it.

function getUserIDandPush($ul){
    global $table_prefix; // Prefix for Database table
    global $user_login;
    global $wpdb; // Wordpress WPDB database method 
    $dt = $table_prefix; //Tables Prefix
    if (!is_user_logged_in() && isset($_SERVER['LOGON_USER'])) {
        $as = $wpdb->get_results('SELECT * FROM '.$dt.'users WHERE user_login = "'.$ul.'" ');
        $usID = $as[0]->ID;
        wp_set_current_user($usID, $ul);
        wp_set_auth_cookie($usID);
        do_action('wp_login', $ul);
    }
}
| improve this answer | |
  • Neat. You could also have (and for paranoia's sake might want to as well) check the length of the $as array is >= 1 before trying to access element 0 - I think that's a more general solution for problems like this. – Rup Apr 19 '16 at 19:35
  • tried that prior to this attempt but it returned a Non-Object error, but great suggestion. – Cam Apr 19 '16 at 19:41
  • Please add an explanation to your answer: why could that solve the problem? – fuxia Apr 19 '16 at 19:42
  • I noticed that on the site, when I printed it would give me an Array with everything including the object... then it gave me a array() which was empty... That led me to believe the issue is in relation to the fact its running multiple times. – Cam Apr 19 '16 at 19:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.