Shinji3rd Shinji3rd - 1 year ago 59
PHP Question

Unserialize a value obtained from the db on php

I need to do something that I am sure it is simple, but I read and read information everywhere and can't find the solution for this. I know, I am a noob, but I really don't know what else to try now.

There is a line on one of the php files of my website's theme, that is like this:

global $post;
if (!is_page()) {$category_ID = get_post_meta($post->ID, '_category_permalink', true);}
else {$category_ID = '';}
$category_parent = pa_category_top_parent_id ($category_ID);

The thing is that '_category_permalink' value on the database is not always an integer number, and I need it to. Sometimes the value is a serialized value, something like this:


So, $category_ID sometimes is 23 (or any other number), and other times is a:1:{s:8:"category";s:2:"23";} (and other values too).

What I need to do is something that can check is the value obtained after that line is an integer or not. In case it is, I need to unserialize it and convert it to its corresponding integer number, stored in the "category" section of that serialized value (from my example, the number 23), so $category_ID will always be equal to an integer number and not a serialized value.

How can I do it?

Thanks in advance :)


This has been solved, the code ended up like this

if (!is_page()) { $category_ID = get_post_meta($post->ID, '_category_permalink', true); } else {$category_ID = '';}
global $wpdb;
$catmeta = $wpdb->get_row("SELECT post_id, meta_key, meta_value FROM MYDATABASENAMEHERE WHERE post_id = '".$post->ID."' AND meta_key LIKE '_category_permalink'",ARRAY_A);

$catmeta = unserialize($catmeta['meta_value']);
$catmeta['meta_value'] = $catmeta['category'];

$category_parent = pa_category_top_parent_id ($catmeta['meta_value']);

Answer Source

First check if $category_ID is a number using is_number().

If not, so use unserialize() to convert it to array and check category:

if (is_number($category_ID)) {
     # $category_ID is number, use it
     # your code here...
} else {
    # $category_ID is a serialized value
    $cat = unserialize($category_ID);
    $category_ID = intval($cat['category']);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download