unserialize data from mysql table and output via php? - php

My wp_usermeta table has 4 columns, umeta_id | user_id | meta_key | meta_value
Image of table:
One of the columns has serialized data - wp_s2member_custom_fields. How can I unserialize from mysql or output with php to see all of my users data within the serialized column?
Here is a breakdown of the serialized data:
wp_s2member_custom_fields
a:12:{
s:7:"country";
s:2:"CA";
s:4:"city";
s:8:"Brampton";
s:5:"state";
s:7:"Ontario";
s:8:"zip_code";
s:6:"L6T4E7";
s:3:"age";
s:13:"25–34 years";
s:8:"blog_url";
s:22:"http://www.blog.com";
s:16:"blog_description";
s:106:"A blog about blogging";
s:15:"monthly_uniques";
s:4:"1000";
s:13:"facebook_page";
s:55:"http://www.facebook.com/myfacebookpage";
s:14:"facebook_likes";
s:3:"1428";
s:15:"twitter_account";
s:31:"http://twitter.com/mytwitterpage";
s:17:"twitter_followers";
s:3:"5849";}

Fetch the data from the database and use PHP's unserialize(). There's no way of doing this in MySQL (or any other DB) and it's the main reason that most developers prefer to just write comma-separated valies in their tables.

WordPress stores arrays/objects in the database by serializing them, so usually the retrieval function is what you want to look for since it will return the data unserialized.
In this case, it's user_metadata, so you need to use the function get_user_meta(), which you provide the $user_id and $key parameters to retrieve it.
In your example, it would be something like this:
<?php
$array = get_user_meta(760, 'wp_s2member_custom_fields');
var_dump($array);
I hope that helps and makes sense...
NOTE:
The WordPress Codex is a priceless resource!

Related

Is it possible to hide the real column name from a table during json_encode time?

I am encoding a php array into json format which have data from a table.
My json_encode produces result with real column name of that table.I want to use the real column name in php side and after it encode to json format I will like to use some other custom name so, that if some user checks in .js file it won't be any problem for me.Below code is the result of json_encode.
What is now :-
{"result":[{"pals_id":"20","from_user":"hancy061","to_user":"hari061","username":"hancy061"}
What I want :-
{"result":[{"pid":"20","fu":"hancy061","tu":"hari061","un":"hancy061"}
Ya, there isn't any need to show user column name and it seems unsecure too.You guys can see what i want have the json_encode format which I want it to be.Is it possible from php side?I mean in php side before encoding the array into json format can we first make custom name of those columns?
You cannot safely replace these columns on the client-side, because it will be available to a user somehow. If you want a user to never learn how your columns are actually named, you should do this at the server-side.
The most common way is to use SQL aliases.
In your PHP change your SQL query to the following:
SELECT pals_id AS pid, from_user AS fu, to_user AS tu, username AS un FROM YourTable ...
However, that's a security through obscurity and doesn't provide any safety.
If you have an SQL-injection vulnerability, then a hacker will be able to query your data structure from system tables or simply SELECT *.
You could also manually set the array keys in the format you want before encoding, like:
foreach ($result as $ind => $r) {
$result[$ind] = [ // For PHP Versions < 5.4 use 'array('
"pid" => $r['pals_id'],
"fu" => $r['from_user'],
"tu" => $r['to_user'],
"un" => $r['username'],
]; // For PHP Version < 5.4 use ');'
}
However you would then have to reverse this if data were to be sent back to the server from the client for updates or something.
If that is needed, then you could set up a map to switch between the two.

MySQL query to return json name value

I'm working with a table in which information is stored in a table in JSON format. The JSON value field looks like:
select * from k2_extra_fields where id = 2 and published = 1;
id | value
2,[{"name":"Apples","value":1,"target":null,"alias":"","required":0,"showNull":1},{"name":"Pears","value":2,"target":null,"alias":"","required":0,"showNull":1},{"name":"Mangos","value":3,"target":null,"alias":"","required":0,"showNull":1},{"name":"Guava","value":4,"target":null,"alias":"Fruit","required":0,"showNull":1},{"name":"Pineapple","value":5,"target":null,"alias":"Fruit","required":0,"showNull":1}]
Or values in a simple line by line view (minus the ID):
[
{"name":"Apples","value":1,"target":null,"alias":"","required":0,"showNull":1},
{"name":"Pears","value":2,"target":null,"alias":"","required":0,"showNull":1},
{"name":"Mangos","value":3,"target":null,"alias":"","required":0,"showNull":1},
{"name":"Guava","value":4,"target":null,"alias":"Fruit","required":0,"showNull":1},
{"name":"Pineapple","value":5,"target":null,"alias":"Fruit","required":0,"showNull":1}
]
The query that leads me here returns the value of 3. 3 = Mangos. How do I take the '3' value and match it up with the stored names/values so that I end up with the output, Mangos?
It should be possible with build in mysql functionality, but very hard and 'not clever' idea to do. If you really need to compute this problem within mysql, you would need to actually add new funtionality to your mysql. Look up on UDF plugins: http://dev.mysql.com/doc/refman/5.1/en/udf-compiling.html

Select a text field from mysql in php

usersim interested how do i select a text field form my mysql database, i have a table named users with a text field called "profile_fields" where addition user info is stored. How do i access it in php and make delete it? I want to delete unvalidate people.
PHP code
<?php
//Working connection made before assigned as $connection
$time = time();
$query_unactive_users = "DELETE FROM needed WHERE profile_fields['valid_until'] < $time"; //deletes user if the current time value is higher then the expiring date to validate
mysqli_query($connection , $query_unactive_users);
mysqli_close($connection);
?>
In phpmyadmin the field shows (choosen from a random user row):
a:1:{s:11:"valid_until";i:1370695666;}
Is " ... WHERE profile_fields['valid_until'] ..." the correct way?
Anyway, here's a very fragile solution using your knowledge of the string structure and a bit of SUBSTRING madness:
DELETE FROM needed WHERE SUBSTRING(
profile_fields,
LOCATE('"valid_until";i:', profile_fields) + 16,
LOCATE(';}', profile_fields) - LOCATE('"valid_until";i:', profile_fields) - 16
) < UNIX_TIMESTAMP();
But notice that if you add another "virtual field" after 'valid_until', that will break...
You can't do it in a SQL command in a simple and clean way. However, the string 'a:1:{s:11:"valid_until";i:1370695666;}' is simply a serialized PHP array.
Do this test:
print_r(unserialize('a:1:{s:11:"valid_until";i:1370695666;}'));
The output will be:
Array ( [valid_until] => 1370695666 )
So, if you do the following, you can retrieve your valid_until value:
$arrayProfileData = unserialize('a:1:{s:11:"valid_until";i:1370695666;}');
$validUntil = arrayProfileData['valid_until'];
So, a solution would be to select ALL items in the table, do a foreach loop, unserialize each "profile_fields" field as above, check the timestamp, and store the primary key of each registry to be deleted, in a separate array. At the end of the loop, do a single DELETE operation on all primary keys you stored in the loop. To do that, use implode(',', $arrayPKs).
It's not a very direct route, and depending on the number of registers, it may not be slow, but it's reliable.
Consider rixo's comment: if you can, put the "valid_until" in a separate column. Serializing data can be good for storage of non-regular data, but never use it to store data which you may need to apply SQL filters later.

Save array in mysql database

I want to save extra information before sending the total order to Paypal. For each item I have created a single column in my MySQL database where I want to store it. Now I was thinking to save it as an array which I can read later for creating a PHP page. Extra fields are taken from input form fields.
By using an array can I be sure not to mixup information?
You can store the array using serialize/unserialize. With that solution they cannot easily be used from other programming languages, so you may consider using json_encode/json_decode instead (which gives you a widely supported format). Avoid using implode/explode for this since you'll probably end up with bugs or security flaws.
Note that this makes your table non-normalized, which may be a bad idea since you cannot easily query the data. Therefore consider this carefully before going forward. May you need to query the data for statistics or otherwise? Are there other reasons to normalize the data?
Also, don't save the raw $_POST array. Someone can easily make their own web form and post data to your site, thereby sending a really large form which takes up lots of space. Save those fields you want and make sure to validate the data before saving it (so you won't get invalid values).
The way things like that are done is with serializing the array, which means "making a string out of it". To better understand this, have a look on this:
$array = array("my", "litte", "array", 2);
$serialized_array = serialize($array);
$unserialized_array = unserialize($serialized_array);
var_dump($serialized_array); // gives back a string, perfectly for db saving!
var_dump($unserialized_array); // gives back the array again
Use the PHP function serialize() to convert arrays to strings. These strings can easily be stored in MySQL database. Using unserialize() they can be converted to arrays again if needed.
To convert any array (or any object) into a string using PHP, call the serialize():
$array = array( 1, 2, 3 );
$string = serialize( $array );
echo $string;
$string will now hold a string version of the array. The output of the above code is as follows:
a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}
To convert back from the string to the array, use unserialize():
// $array will contain ( 1, 2, 3 )
$array = unserialize( $string );
<?php
$myArray = new array('1', '2');
$seralizedArray = serialize($myArray);
?>
Store it in multi valued column with a comma separator in an RDBMs table.
You can use MySQL JSON datatype to store the array
mysql> CREATE TABLE t1 (jdoc JSON);
Query OK, 0 rows affected (0.20 sec)
mysql> INSERT INTO t1 VALUES('{"key1": "value1", "key2": "value2"}');
Query OK, 1 row affected (0.01 sec)
To get the above object in PHP
json_encode(["key1"=> "value1", "key2"=> "value2"]);
More in https://dev.mysql.com/doc/refman/8.0/en/json.html

Unserialize values from mySQL

I am using a classified scripts and saves user_meta data in the wp_usermeta table.
The meta_key field is called user_address_info and in it there are all the data like below :
s:204:"a:7:{s:9:"user_add1";s:10:"my address";s:9:"user_add2";N;s:9:"user_city";s:7:"my city";s:10:"user_state";s:8:"my phone";s:12:"user_country";N;s:15:"user_postalcode";s:10:"comp phone";s:10:"user_phone";N;}";
I am not using all the fields on the script but user_add1, user_city, user_state and user_postalcode
I am having trouble to get the data using SQL like the example below (wordpress) :
$mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_A);
I would like some help here so that I will display anywhere (I dont mind using any kind of SQL queries) the requested info e.g. the user_city of current author ID (e.g. 25)
I was given the following example but I want something dynamic
<?php
$s = 's:204:"a:7:{s:9:"user_add1";s:10:"my address";s:9:"user_add2";N;s:9:"user_city";s:7:"my city";s:10:"user_state";s:8:"my phone";s:12:"user_country";N;s:15:"user_postalcode";s:10:"comp phone";s:10:"user_phone";N;}"';
$u = unserialize($s);
$u2 = unserialize($u);
foreach ($u2 as $key => $value) {
echo "<br />$key == $value";
}
?>
Thank you very much.
No, you can't use SQL to unserialize.
That's why storing serialized data in a database is a very bad idea
And twice as bad is doing serialize twice.
So, you've got nothing but use the code you've given.
I see not much static in it though.
do you experience any certain problem with it?
Or you just want to fix something but don't know what something to fix? Get rid of serialization then
i have found that the serialize value stored to database is converted to some other way format. Since the serialize data store quotes marks, semicolon, culry bracket, the mysql need to be save on its own, So it automatically putting "backslash()" that comes from gpc_magic_quotes (CMIIW). So if you store a serialize data and you wanted to used it, in the interface you should used html_entity_decode() to make sure you have the actual format read by PHP.
here was my sample:
$ser = $data->serialization; // assume it is the serialization data from database
$arr_ser = unserialize(html_entity_decode($ser));
nb : i've try it and it works and be sure avoid this type to be stored in tables (to risky). this way can solve the json format stored in table too.

Categories