Question

This one's been bugging me for the past day now. Here's the code:

public function getUserCredits()
{
    $dbl = new databaseManager();
    $dbl->connect_simp();
    $ret = $dbl->queryDB("SELECT * FROM users WHERE `USER_ID` = ".$this->userId);
    $this->userCredits = $ret['USER_CREDITS'];

    return $this->userCredits;
}

Now when I try to run this code, I get an undefined offset error. Nothing too strange about it when I first saw it, but now it's happening more and more and I can't figure out why.

I can use var_dump(); and var_export(); and it displays the contents of the returned array absolutely fine.

EDIT:

    array(1) {
  [0]=>
  array(50) {
    ["USER_ID"]=>
    string(10) "0000000001"
    [0]=>
    string(10) "0000000001"
    ["USER_USERNAME"]=>
    string(8) "SampleUsername"
    [1]=>
    string(8) "SampleUsername"
    ["USER_PASSWORD"]=>
    string(32) "5f4dcc3b5aa765d61d8327deb882cf99"
    [2]=>
    string(32) "5f4dcc3b5aa765d61d8327deb882cf99"
    ["USER_EMAIL"]=>
    string(0) ""
    [3]=>
    string(0) ""
    ["USER_LEGION"]=>
    string(1) "1"
    [4]=>
    string(1) "1"
    ["USER_ENERGY"]=>
    string(4) "2812"
    [5]=>
    string(4) "2812"
    ["USER_MAX_ENERGY"]=>
    string(4) "2812"
    [6]=>
    string(4) "2812"
    ["USER_SHIELD"]=>
    string(2) "20"
    [7]=>
    string(2) "20"
    ["USER_MAX_SHIELD"]=>
    string(2) "20"
    [8]=>
    string(2) "20"
    ["USER_HULL"]=>
    string(2) "60"
    [9]=>
    string(2) "60"
    ["USER_MAX_HULL"]=>
    string(2) "60"
    [10]=>
    string(2) "60"
    ["USER_CREDITS"]=>
    string(19) "9223372036854775807"
Was it helpful?

Solution

try

$ret[0]['USER_CREDITS']

instead of

$ret['USER_CREDITS']

OTHER TIPS

You gotta fetch a row first (I assume you extend mysqli).

$result = $dbl->queryDB("SELECT * FROM users WHERE `USER_ID` = ".$this->userId);
$row = $dbl->fetch_assoc($result) ;

$this->userCredits = $row['USER_CREDITS'];

At first you should watch the result record. As you are getting the details in an array of your database record fetched and it is in array format with numeric keys. Use what @AbuOmar said.

AS your var_dump($ret), Try this to assign user credit otherwise if it is not set, assign 0 value.

if(isset($ret[0]['USER_CREDITS'])){
    $this->userCredits = $ret[0]['USER_CREDITS'];
}
else{
    $this->userCredits = 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top