Calling a key of a json_decoded array return NULL

丶灬走出姿态 提交于 2019-12-25 05:33:12

问题


I am struggling to understand why certain cases that specific way to access the key in PDO works while when I tried myself, it didn't.

For example,

$sth = $this->dbh->prepare("UPDATE eq_question SET ". $user->field ."=? WHERE questID=?");

this PDO accessed an array's key (which was in a javascript object then posted and json_decoded in PHP) with $user->field, but when I tried to simulate the decoded array and use var_dump ($user->field), I will receive NULL.

Can anyone tell me why is it happening?

In the example below, when I var_dump ($user), I can see all the keys, but when I do var_dump($user->field), I only receive null, therefore, cause the class's updateValue fail.

An example to see what I mean:

class User {

    private $dbh;

    public function __construct($host,$user,$pass,$db)  {   
        $this->dbh = new PDO("mysql:host=".$host.";dbname=".$db,$user,$pass);           }
public function updateValue($user){ 
$sth = $this->dbh->prepare("UPDATE eq_question SET ". $user->field ."=? WHERE questID=?");
$sth->execute(array($user->newvalue, $user->id));
}


$user = new stdClass;
echo " <br>|||SPACE||| BEFORE ASSIGN A OBJECT OT THE ARRAY-  ";
$userParams = array('id' => 1, 'field' => 'questTitle', 'newvalue' => "Baaaaa");
var_dump($userParams);
$user = json_encode(array("user"=>$userParams));
echo " <br>|||SPACE||| BEFORE DECODE-  ";
var_dump($user);
echo " <br>|||SPACE||| BEFORE DECODE of field-  ";
var_dump($user->field);
$user = json_decode($user);
echo " <br>|||SPACE||| AFTER DECODE-  ";
var_dump($user);
$userN=new User(...//info is hided by intention!); 
$dump=$userN->updateValue($user);
echo " <br>|||SPACE||| PRINT-----  ";
print($dump);
echo " <br>|||SPACE||| VAR_DUMP-----  ";
var_dump($dump);

Thank You

来源:https://stackoverflow.com/questions/20383568/calling-a-key-of-a-json-decoded-array-return-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!