Updating Serialized value in mysql - php

I want to update a Serialized value on meta_value column on mysql table.But json is hard to select from sql . How can i achieve.
a:2:{i:0;a:2:{s:19:"sevent_speaker_name";s:8:"John Doe";s:18:"sevent_speaker_img";a:1:{i:0;s:5:"72921";}}i:1;a:2:{s:19:"sevent_speaker_name";s:10:"John Smith";s:18:"sevent_speaker_img";a:1:{i:0;s:5:"72922";}}}
Here is the value. I want to replace all sevent with elevent but how can i do it?
Can I use LIKE? But first it need to be unserialized?.

This encoded information probably comes from WordPress or some other PHP framework's database; it's not JSON. Note that strings are encoded by storing the string length and the string contents:
s:19:"sevent_speaker_name"
You can use MySQL's REPLACE function to replace sevent with elevent, but you must be careful to update the length value s as well, or WordPress/PHP won't be able to read in the data.
It's possible to write a MySQL query to update the specific example given above, but it's difficult to write a query to substitutes all strings generically. Here is a tool that does the work.

Related

Unserializing data

I have some order info stored in a DB table row called "order_details". From what research I've done so far, the cells contain a serialized array:
s:346:"{"total":50,"tax_perc":8.25,"shipping_total":20,"discount_total":0,"discount":"","pick_up":0,"items":[{"id":"0","amount":1,"available":1000,"price":50,"first_pet":50,"pet_count":1,"size":"4x6","type":"portrait","clothe":"93","total":50}],"size_found":false,"taxes_total":4.13,"grand_total":74.13}";
I tried using unserialize() but that didn't print anything. Leaving it serialized at least printed the contents of the cell.
Any ideas on why nothing is being printed when I use unserialize()?
Also, I'm trying to create a back-end interface using this data, so given that unserialize() will organize this data, I need to be able to show only a particular element (like ID). Is that possible? Or will it have to print all of that data?
UPDATE
Here's how what I have so far works:
(1) When someone places an order, the data is serialized and thrown into the db and an email is sent to both me and the client
(2) For this Admin page where I want to ask for and show said serialized data, I query the db to return the relevant table ordered by id
(3) Then I have this, which is meant to throw that data into a table row on the UI.
$mydata = $all_orders[$i]['order_details'];
$mydata = unserialize($mydata);
echo '<td>' . $mydata . '</td>';
At this point I am just trying to get a better visual on that data. I was also hoping to be able to maybe sort the table on price, ID, etc.
Thanks in advance for your responses!
The strings in your database have been JSON encoded to a string, then serialized. That's why the first character in the serialized string is an "s" (s means whatever follows is a string, in your case, of 346 characters in length).
The reason that unserialize() is returning false is because the string that has been serialized contains unescaped double quotes. When unserialize() runs, it fails as it uses the first 2 sets of double quotes to determine the string to unserialize. In your case, unserialize() is trying to unserialize the following string:
s:346:"{"
This causes a failure, as the string between the two sets of double quotes isn't 346 characters long.
You shouldn't need to serialize something that has already been JSON encoded. Choose one of the encoding options (JSON encoding or serializing) but not both, and stick with the one that you choose.

how to save json string in a mysql field

I have a table with a text field. I received string as below:
"value": "{\"airwayBills\":[\"84498761\"],\"dockets\":[\"1652395\"],\"error\":false,\"muditaError\":[{\"actionType\":\"docket\",\"docketNo\":\"1652395\",\"errorMessage\":\"No thing error\",\"pieceList\":null,\"quantity\":\"1\"}],\"muditaManifestExtra\":\"Unknown\",\"thingDetails\":[{\"airline\":\"Unknown\",\"bookingDate\":\"19-05-2014 13:03:15+0530\",\"currentPiecesDelivered\":\"0\",\"currentPiecesManifested\":\"1\",\"destination\":\"GOI\",\"flight\":\"Unknown\",\"inScannedPieces\":[],\"locationId\":\"MUDDELHUB1\",\"mode\":\"Air\",\"number\":\"1652395\",\"ordinality\":\"0\",\"origin\":\"DEL\",\"outScannedPieces\":[],\"quantity\":\"1\",\"recipientEmailId\":\"Unknown\",\"serviceProvider\":\"Unknown\",\"shipper\":\"Vector E Commerce Pvt. Ltd.\",\"thingType\":\"docket\",\"totPiecesManifested\":\"1\",\"totalPiecesDelivered\":\"0\",\"weight\":\"11\"}]}",
This value get stored correctly inside a field in the table, but when I try to fetch this value and save it in another field of another table then some of the values like "airwayBills\":[\"84498761\"] are stored as "airwayBills\":["0"], this is causing the loss of data. There is one more strange behaviour that this is happening randomly with only some of the records. Some records are added correctly. For saving into another field I am just enclosing the string in a single quote to save the string as is.
Please help how to save it in a single field in Mysql. Please note that the above values are coming after a GROUP_CONCAT query on the first table.
Thanks in advance
Consider the variable name $json_string as the one that contains your json in the give state (in your post), try stripslashes before trying to insert it into the database.
Here's an extra question, are you building the json array manually using string concatenation or using php array and them json_encode ? (2nd one would make things easier for you, since when you need to add the json obtained after the first mentioned query ran you can just do json_encode and your done)

MySQL select spatial field value and convert to WKT with PHP

If selecting a spatial field value from MySQL without converting it to text in the query, I get an "unreadable" string in PHP. Which function can I use to convert this to WKT?
Example:
SELECT AsText(polygon_field) FROM Table; // gives a nice WKT string.
SELECT polygon_field FROM Table; // gives an unreadable (binary?) string.
Due to limitations in the framework we use, it would be great if that string could be converted to WKT using PHP. Any ideas on what function to use? Can't seem to find anything, because all examples I find rely on the MySQL function AsText :-(
The result is the internal format of the column of MySQL (see the manual on fetching values). This format is neither WKB (well known binary) nor WKT (well known text).
I would not expect any other software to be able to parse those values, especially since MySQL provides the helper functions AsText and AsBinary, which are easy to use (if one does not use a hindering framework).
You can create a view, which contains the AsText output of the column as the column itself. This only helps you while selecting, but maybe that is all you need.

Unserializing PHP array in SQL

One of the former developers in an old system I'm working on used PHP serialize() to flatten one array of data into one column of a MySQL table.
I need to write a complex query that involves this column. Is there a way to unserialize the data (even if it's into a comma separated string) within the SQL query or do I need to pass the results back to PHP?
Serialized PHP data is just a string, so for "simple" searches, you can use basic MySQL string operations.
e.g. The serialized array has a name parameter and you need to match against that, so
... WHERE LOCATE(CONCAT('s:', LENGTH('foo'), ':foo') ,serializeddatafield) > 0
which would produce
WHERE LOCATE('s:3:foo', serializeddata) > 0
But then, this would find ANY strings whose value is foo anywhere in the data, and not necessarily in the particular array field you want.
e.g. you're probably better off yanking out the whole field, deserializing in PHP, and then doing the search there. You could use the above technique to minimize the total number of strings you'd have to yank/parse, however.

How do i store a field from a MySQL database as a string in PHP?

One of my fields in my data base is an array which has been converted to a string using the implode() function.
How do I retrieve the contents of this field (LESSONS) from the database and store it to a string when a user entered value is equal to the the value of the field NAME?
Thanks in advance for any help you may be able to provide.
Here you go:
$r = mysql_query('SELECT LESSONS FROM TABLE WHERE NAME=\'user_string\'');
$rows = mysql_fetch_assoc($r);
echo $rows['LESSONS'];
I don't know if I understood your question but... Take a look about Stored Procedures
If you used the implode function to convert your array into a string, then this data has lost any information about the array keys.
As far as you want to convert the data back, use the explode function:
$array = explode(',', $columnData);
But You can therefore not search for array keys within the database.
Next to that, the MySQL database (I assume you're using MySQL) can not search for array keys anyway.
You need to store the data in some other way into the mysql to search for it in an SQL later on.
For example, you can create a table that stores key/value combinations with a grouping index.
However MySQL has some string functions that can help you searching within the (now) string data in the MySQL database.
When searching for a value, before the comparison add a comma at the beginning and one at the end of the string. There is a MySQL string function that can concatenate strings. Then search within that expression for your value with a comma added in front and back as well.
Then you can lookop a single array element within the mysql database. MySQL String Functions.
This is a quick solution only, this won't work on large databases performant. However it might solve your problem w/o changing your database structure.

Categories