WPDB query – decrypting DB data

I am trying to grab data from the DB using WPDB but I am stuck on how to decrypt the data e.g.

The data is stored as: a:2:{i:0;s:2:”92″;i:1;s:2:”71″;}

Read More

I want the 92 & 71 as that’s my post IDs, how to I get that part from the DB using WPDB?

My code so far is:

$crosssells = $wpdb->get_results(
 "SELECT * 
  FROM $wpdb->postmeta
  WHERE _crosssell_ids != '' 
 "
);

The table is only created when data is in putted in the post so I need to check if the table exists and then grab the post id’s

Related posts

1 comment

  1. It’s just serialized, in WordPress, you can run maybe_unserialize and get back the variable/array.

    $crosssells = $wpdb->get_results(
        "SELECT * 
      FROM $wpdb->postmeta
      WHERE _crosssell_ids <> '' 
     "
    );
    
    $array = maybe_unserialize($crosssells);
    

    However, there are built in functions to retrieve posts based on meta information. You can use get_posts to retrieve the posts and get_post_meta to retrieve meta information from a specific post id. It’s best to abstract away from direct database interaction to take advantage of the built in caching, security, etc of WordPress.

Comments are closed.