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.
Related
For the past 2 days I have been looking over the internet on how to handle data stored as json in mySQL database.All I found was a single article in here which I followed with no luck.So here is my question
This is my table called additional with 2 columns only...jobid and costs. jobid is an int of length 5 and obviously the primary key, costs is simply stored as text. Reason I combined all the costs under one column is because the user in my application can put whatever he/she wants in there, so to me the costs is/are unknown. For example one entry could be
24321 , {"telephone" : "$20"}
or
24322 , {"telephone" : "$20", "hotel" : "$400"}
and so on and so forth but I hope you get the point.
Now given this example I need to know how to handle data in and out from the database stored as json using php. So insert, select and update but I think with one given example I can do the rest If someone can help me understand how to handle json data in and out from a database.
Oh and one last thing. Not only I need to know how to fetch the data I need to be able to separate it too e.g:
$cost1 = {"telephone" : "$20"};
$cost2 = {"hotel" : "$400"};
I really hope someone can help with this because like I said above I spent 2 days trying to get my head around this but either no articles on this matter(except the one from this site) or completely irrelevant to my example
You tagged it as PHP so you can use php functions: json_encode and json_decode.
For example when you read (SELECT) and got this cost value in string corresponding to the primary key 24322:
//after you query db and got the cost in string...
$sql = "SELECT * FROM additional";
$result = mysqli_query($conn,$sql); $row = mysqli_fetch_array($result);
//from your comment below.... just changed to $cost so I don't have to change everything here...
$cost = $row['costs'];
//$cost = '{"telephone" : "$20", "hotel" : "$400"}'
//you just have to:
$cost = json_decode($cost);
// result in an object which you can manipulate such as:
print_r($cost->telephone);
// $20 or:
print_r($cost->hotel);
//$400;
//or if you want to go through all of the costs... you change that to array:
$cost = (array)$cost; //or on your json_decode you add a TRUE param... ie(json_decode($cost, TRUE))...
print_r($cost);
//will produce an associative array: ['telephone'=>'$20', 'hotel'=>'$400']
//for which you can do a foreach if you want to go through each value...
On the other hand when you save to db with an object:
$cost = (object)['hotel'=>'$300', 'taxi'=>'$14'];
//you json_encode this so you can write to db:
$cost = json_encode($cost);
//a string... you can then use $cost to write to db with (insert, update, etc)
Note: json_decode needs the input string to be UTF-8 encoded. So you might need to force your mysql server to provide UTF-8. Some reading: https://www.toptal.com/php/a-utf-8-primer-for-php-and-mysql
Hope this helps...
You can use json_encode() and json_decode() throughout your update or insert process.
Basically
json_encode() takes Array and returns JSON as String
json_decode() takes JSON as String and returns Array
http://php.net/manual/en/function.json-encode.php
So in your case whenever you want to update 24321 , {"telephone" : "$20"}
you got to decode like
$array = json_decode($row['jsonDataOrWhateverTheColumnNameIs'],true);
$array['telephone'] = "40$";
...
...
$jsonString = json_encode($array); // Use this string with your update query.
I have an external database that I am trying to access from within a Drupal page, I have successfully queried the database and output data to the page using fetchAssoc(), however this only returns the first row in the database. I would like to return all rows into an array for processing, so I'm attempting to use fetchAllAssoc(), this however results in an exception. The database has the following SQL fields:
id, model, manufacturer, url, date_modified
My test code is as follows:
<?php
db_set_active('product_db');
$query = db_select('product', 'p')->fields('p');
$sqlresults = $query->execute()->fetchAllAssoc('id');
foreach($sqlresults as $sqlresult)
{
printf($sqlresult);
}
db_set_active();
?>
I'm thinking that it is the key field 'id' that I am specifying with fetchAllAssoc() that is the problem, as fetchAssoc() prints values correctly. All documentation I have found seems to say that you pass a database field as the key but I have also passed a numeric value with no success.
Many thanks in advance for any advice, I'm sure I'm just missing something stupid.
I think it should work in this way, but within the foreach you want to print the $sqlresult variable as a string, but it is an object (it causes the error).
printf function needs a string as the first parameter, see:
http://php.net/manual/en/function.printf.php
Use for instance var_dump instead:
var_dump($sqlresult);
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.
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.
I am attempting to grab a date supplied via POST, then generate a list of dates over a 12 week period from the supplied start date. These dates would then go into the DB and a 12 week schedule would be output, which the user can interact with (add/edit/delete).
I am successfully taking the start date, generating the 12 week date list and adding this into the DB in serialized form, but when it comes to selecting the dates for display, I get the following error:
Notice: unserialize() [function.unserialize]: Error at offset 0 of xxx bytes in ...
Here is my code:
1st .php file here to take a form input (a date) and then get a list of each date over a 12 week period from the start date, and insert into the DB:
The array:
$start = strtotime($_POST['Start_Date']);
$dates=array();
for($i = 0; $i<=84; $i++)
{
array_push($dates,date('Y-m-d', strtotime("+$i day", $start)));
}
$savetodb = serialize($dates);
The insert:
$sql = "INSERT INTO programme VALUES (NULL, '20', '".$_POST["Start_Date"]."' , ' ".$savetodb." ', '".$_POST["Programme_Notes"]."')";
2nd .php file here - SELECT and unserialize:
$result = mysql_query("SELECT Programme_Dates FROM programme");
while($row = mysql_fetch_array($result))
{
$dates = unserialize($row["Programme_Dates"]);
echo $dates;
}
From what I've read the problem could be related to the DB column where the serialized array is inserted (ie being too small), but it is set to TEXT so that should be fine right? I also thought there may be certain characters within a date causing problems, but when testing with a "regular" array (ie just text), I get the same errors.
Any suggestions / hints much appreciated, thanks.
Why are you using stripslashes? My bet is that is the problem. Remove that from there and see if it works.
As a side note, stripslashes should be avoided as if data is probably inserted into the database they should be escaped properly meaning no extra slashes should be added. If you need to stripslashes from the data itself I would suggest using something like array_filter after you unserialized the array.
EDIT
You should also look into SQL Injection and how to prevent it, as your code is suseptible to be exploited.
UPDATE
Looking further at your code you insert the serialized array with 2 extra spaces: ' ".$savetodb." ', try using just '".$savetodb."', that and see if it fixes your issue.
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.