php – json_decode showing no data-ThrowExceptions

Exception or error:

I’m using below logic to store data in JSON format in MySQL using PHP.

foreach ($_POST['data'] as $key => $value)
    {
        if($value[1] == "page_keywords")
            $store .= json_encode(array($value[1] => $value[2]));
        else
            $store .= json_encode(array($value[1] => trim($value[2])));
    }

session_start();
$date = new Date();
$modified = $date->getDate();

$query = ' UPDATE pages SET last_updated_user_author_id = "'.$_SESSION['user_id'].'", data = "'.htmlentities($store, ENT_QUOTES).'", modified = "'.$modified.'" WHERE id = "'.$pageID.'" ';

Then while decoding the data i’m using below logic:

$query = ' SELECT data FROM pages WHERE id = "'.$_POST['pageID'].'" ';
$connection = $this->establish_connection();
$data = $connection->query($query);
$connection->close();
if($data->num_rows > 0)
    {
        while($row = $data->fetch_assoc())
            {
                $var = html_entity_decode($row['data']);
                echo json_decode($var);
            }
    }

While json_decode it shows no data in response, when i did var_dump it shows null, but if i did not do json_decode and only used html_entity_decode() i get below output

{"page_base_url":"http://www.myblog.com/about/contact/"}{"page_url_revision":"http://www.myblog.com/about/contact/"}{"page_url_alternate":"http://www.myblog.com/about/contact/"}{"page_url_shortlink":"http://www.myblog.com/about/contact/"}{"page_url_canonical":"http://www.myblog.com/about/contact/"}{"page_title":"Example | Contact"}{"page_name":"Example Contact"}{"page_type":"WebSite"}{"page_meta_description":"Want to get in touch with us? You're on the correct page, you can get in touch with us by filling the form below. We will get in touch with you with 24 hours."}{"page_keywords":["example","contact","support","help","getintouch","feedback","bug","updates"]}

I’m not sure where i’m going wrong, could anybody help me out here?

I want to give an eccho in json_encode format as a response to ajax call. i use below logic to do so

echo json_encode(
                array(
                        "type" => "error",
                        "status" => "Error While Retrieving Data!",
                        "message" => $error
                     )
            );
How to solve:

I think you need something like:

$store = array();
foreach ($_POST['data'] as $key => $value)
    {
        if($value[1] == "page_keywords")
            $store[] = array($value[1] => $value[2]);
        else
            $store[] = array($value[1] => trim($value[2]));
    }

$save = json_encode($store);

or even (if your $value[1] is always unique within the loop)

$store = array();
foreach ($_POST['data'] as $key => $value)
    {
        if($value[1] == "page_keywords")
            $store[$value[1]] = $value[2];
        else
            $store[$value[1]] = trim($value[2]);
    }

$save = json_encode($store);

then use $save to store in your table. I’m not 100% on that, though.

Answer:

The string you’ve shown is not valid JSON. If you wanted to store a list of objects like that in JSON format, they need to be within an array, and separated by commas. Otherwise they are just unrelated individual objects and cannot be decoded as a single block of JSON.

Therefore you need to build an array in PHP and then encode the whole thing at the end. Something like this:

$storedata = array();
foreach ($_POST['data'] as $key => $value)
{
    if($value[1] == "page_keywords")
        $storedata[] = array($value[1] => $value[2]);
    else
        $storedata[] = array($value[1] => trim($value[2]));
}

$jsondata = json_encode($storedata);

And then use $jsondata in your SQL statement.

Answer:

Your problem is your “saving” to the database. You encode every key-value-pair in an own json-string and concat those json-strings.

Your snippet

foreach ($_POST['data'] as $key => $value)
{
    if($value[1] == "page_keywords")
        $store .= json_encode(array($value[1] => $value[2]));
    else
        $store .= json_encode(array($value[1] => trim($value[2])));
}

Yields $store = "{key1:value1}{key2:value3}{key3:value3}". Note all the brackets, you have 3 distinct json-objects with a single key-value pair in your string, instead of one json-object with 3 key-value-pairs.

However, I assume you want a single json-object with the key-value-pairs as result like the folling?

$store = "{
    key1:value1,
    key2:value2,
    key3:value3
}";

If so, you need to build your array differently:

$store = array();
foreach ($_POST['data'] as $key => $value)
{
    if($value[1] == "page_keywords")
        $store[$value[1]] = $value[2];
    else
        $store[$value[1]] = trim($value[2]);
}

And please, for the safety of everyone, your code is vulnerable of sql-injections. Please fix that, too.

Leave a Reply

Your email address will not be published. Required fields are marked *