LankyMoose LankyMoose - 6 months ago 7
PHP Question

PHP Associative array from encoded data

I'm kinda new to php and mysql so this could be something as simple as a syntax error or something but I'm having no luck with using other examples.

The array in my db (JSON encoded):

["[\"option1\"=\u003E\"1\",\"someotherthing\"=\u003E\"abc\"]",""]


Fetching JSON encoded array from UserData:

if ($stmt = $con->prepare("SELECT UserData FROM users WHERE Username=?")) {
$stmt->bind_param("s", $Username);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_assoc();
$json = json_decode($data['UserData']);
echo $json[0];
}


Result:

["option1"=>"1","someotherthing"=>"abc"]


Why is it that replacing "echo $json[0];" with "echo $json['option1'];" won't work, although the array is decoded?

EDIT: got it sorted! Does the trick by using the following:

if ($stmt = $con->prepare("SELECT UserData FROM users WHERE Username=?")) {
$stmt->bind_param("s", $Username);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_assoc();
$json = json_decode($data['UserData']);
$array = json_decode(json_encode($json),true);
echo $array['test'];
}

Answer

This isn't the best way to go about storing data. As you see, it's being stored in your database as a (string). If you're looking to access the variables in this array then you're going to have a hard time!

A more "common" way of achieving what you're after is storing JSON in the database and accessing it.

//....other code....
$data = $result->fetch_assoc();
$json = json_decode($data);

echo $json->someotherthing;

As @Sean noted in his comment, you're fetching a collection of data instead of one row. You can do that by harnessing $MYSQLI->fetch_assoc() to return an associative array.


Edit

This is an edit to your question. You're still storing a string array as json. That's why you can't access it. I assume you have an actual array. This is the way you'd want to store said data:

// example array
$array = array('test' => 'hello', 'derp' => 'herp');
// encode it
$json = json_encode($array);
// store it
// DO YOUR MYSQLI INSERT, ETC...
Comments