Read and Write PHP Array in MYSQL - php

I want to save a PHP associative array from a PHP varible to a MYSQL database, then later access the stored value (within the MYSQL database) and use it within PHP as an associative array.
$arr = array("abc"=>"ss","aaa"=>"ddd");
now i want to save
array("abc"=>"ss","aaa"=>"ddd");
to the database and again want to retrive it and assign it to variable.
I tried to use the serialize function, but it only saved the word "Array" into database.

One way to do this is to serialize it into a string before insert, and then deserialize it into array after fetching. There are different ways to do that, but if your arrays are simple, JSON is an acceptable serialization format.
You could json_encode on the way in:
$str = json_encode($arr);
// Insert $str into db
Then json_decode later:
// Got $str from db
$arr = json_decode($str);
Another method is serialize:
$str = serialize($arr);
// Insert $str into db
And unserialize:
// Got $str from db
$arr = unserialize($str);
This will allow more possibilities for what you can serialize than json_encode and json_decode, but it will be harder to inspect the database manually to see what's in there.
So both methods have advantages and disadvantages. There are other serialization/marshal formats out there too.

As Ben said, you need to serialize your array before storing it in the database then unserialize it when you read it back. If 'Array' is being written to your database then you are probably not saving the results of serialize() to the variable that you are writing.
<?php
function store()
{
$arr = array("abc"=>"ss","aaa"=>"ddd");
$serialized = serialize($arr);
// Store $serialized to the database
}
function retrieve()
{
// Retrieve $serialized from the database
$arr = unserialize($serialized);
}

Related

PHP and JSON datatype in MySQL

Despite of recent implementation of JSON datatype to MySQL I can't find any word on it in the related PHP documentation.
My question is: will PHP automatically convert cells of JSON column to the actual values - arrays or literals - or will it provide just json-encoded strings. Like:
$sql_query = "SELECT JSON_ARRAY(1,2,3)";
$result = mysqli_query($sql_query);
$value = mysqli_fetch_row($result)[0];
// what is a $value? Array(1,2,3) or a string "[1,2,3]"
// do I have to use json_decode() to get an actual array here?
(Don't have MySQL 5.7 at hand right now, so can't check it myself.)
i think with serialize and unserialize you get whatever you want.
so just store all values using serialize and you can get that values with unserialize.
so just check serialize and unserialize.

PHP Unserialize data for use in array - sub standard characters in string

I am using a jQuery plugin of nestable forms and storing the order of these in a database using serialize (achieved through JS). Once I retrieve this data from the database I need to be able to unserialize it so that each piece of data can be used.
An example of the data serialized and stored is
[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]
The number of ID's stored in each serialized data varies and the JS plugin adds the [ and ] brackets around the serialization.
I have used http://www.unserialize.com/ to test an unserialization of the data and it proves successful using print_r. I have tried replicating this with the following code:
<?php
print_r(unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]'));
?>
but I get an error. I am guessing that I need to use something similar to strip_tags to remove the brackets, but am unsure. The error given is as follows
Notice: unserialize(): Error at offset 0 of 70 bytes
Once I have the unserialized data I need to be able to use each ID as a variable and I am assuming to do so I need to do something as:
<?php
$array = unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]');
foreach($array as $key => $val)
{
// Do something here, use each individial ID however
// e.g database insert using $val['id']; to get H592736029375 then K235098273598 and finally B039571208517
}
?>
Is anyone able to offer any help as to how to strip the serialized data correctly to have the ID's ready in an array to then be used in the foreach function?
Much appreciated.
PHP's serialize() and unserialize() functions are PHP specific, not for communicating with other languages.
It looks like your JS serialize function is actually generating JSON though, so on the PHP side, use json_decode() rather than unserialize.
Here's a fiddle
$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $index=>$data){
echo "$index) {$data['id']}\n";
}
Outputs:
0) H592736029375
1) K235098273598
2) B039571208517

When using json_encode to display the contents of a select query, how to name objects?

Disregarding security issues (for now)
I am using json_encode to display the contents of a select query.
I used:
$sql= {query code};
// created a temp array to hold data and an array for all the results
$resultArray = array();
$tempArray = array();
// looped through every object in the result set
while ($row = $result->fetch_object());
// added it into the results array
$tempArray = $row;
array_push($resultsArray, $temparray);
// encoded the array to a json format
echo json_encode($resultArray);
Question: My objects don't have names, so it makes it difficult for me to write any code that could read the results and display them. How do I name the objects? Is it an entry I could add into the table (let's say in a case of different names I could give each object)
You should try to build the array/object structure you want in PHP. That way when you json_encode it, you'll know what it looks like and it will be what you want.
Try:
echo json_encode(array('people' => $resultArray));
In fact this should not work at all. Casting PDO (or MySQLi, as mentioned in comment) objects to JSON. You should use fetch_assoc instad, that would return associative array that could be put directly in JSON structure.

create a dynamic php file and define an array

I need to update some static site data periodically, so i am thinking of keeping it in a format easily and readily available on the server.
I am thinking of creating a php file that can be included in the code, so preparing the data gets separate from the browser requests.
i fetch the data from the db, so i have an array right now in key value format.
now i want to create a php file, that just defines that array.
the key and value will be string based values, and the data is in swedish.
is there a way to directly dump the array to a file, and then just include the file without any preprocessing. I want the file in the following output :
$array = array ();
$array ["key"] = "value";
$array ["key"] = "value";
$array ["key"] = "value";
$array ["key"] = "value";
I would also recommend looking at var_export as you won't have to serialize and encode to use it.
For example (untested):
<?php
$array = array('key' => 'v');
$exported = var_export($array, TRUE);
file_put_contents('/path/to/file', '<?php $var = ' . $exported . '; ?>');
?>
and then you can read it back in via:
<?php
include '/path/to/file';
// and now you have access to $var
// of course you may want to change the name of the $var variable as it
// will be brought into global scope (and might conflict)
?>
Use PHP's serialize and base64_encode functions and write the result to file.
When you want to use the data: simply read the file, decode and unserialize:
<?php
// dump data
$array = array("key"=>"value");
file_put_contents("test_data.txt", base64_encode(serialize($array)));
// retrieve data
$string = file_get_contents("test_data.txt");
$data = unserialize(base64_decode($string)));
var_dump($data);
Encoding the array in base64 will allow you to safely write binary data to the file (eg. extended character sets).
You can directly write the code into the file fwrite($handle, "$array = array();"); then doing an eval() on the file content you're reading back. It'll work, but its dangerous because if any malicious code is put into the text file, it will be executed.
I recommend you take a look at serialization: http://php.net/manual/en/function.serialize.php and write serialized data that you unserialize back into an array. It's much safer.

,what is the use and benefit of Serialize() function in php

I know its Generates a storable representation of a value and used to access the objects across the php files but what if i dont use this function while storing the objects.
Let's say you have some post data, but your database/persistent storage can't be modified to store the new post data in separate fields.
You could serialize your $_POST array and store it in the persistent storage you've got. It's useful for generating user-based CRUD applications. I've found the necessity of storing the POST as a "payload" of sorts quite invaluable at times.
Knowing you can do something, doesn't mean you have to use it everywhere.
That is easly explained by reading the official PHP page that states:
Generates a storable representation of a value
This is useful for storing or passing PHP values around without losing their type and structure.
Basically you can serialize an object write the string in a file and on another request you can simply read the file and unserialize it to have the final object loaded.
When you want to store or send data in a "safe" format, preserving PHP type and structure.
For example, you have an UTF-8 string with Japanese text. Or a multidimensional array. You can save it to a text file or insert into a database.
$array = array( 'key' => 'value', 'other_key' => 'other_value');
file_put_contents( 'array.txt', serialize( $array ) );
When you want to use the stored data, you may use the "unserialize" function:
$contents = file_get_contents( 'array.txt' );
$array = unserialize( $contents );
You can serialize values of any PHP type, including objects, but except the "resource" type (database connections, file handlers, etc.)
When you unserialize an object, you must ensure to have loaded its class previously.
More at the PHP manual: http://php.net/serialize
To serialize means converting runtime variables into consistent form.
Often this is a simple string or XML representation of the code segment.
Usage:
<?php
$user = new UserObjectFromDatabase();
$data = serialize($user);
http_reqeust_send($to = "some remote server", $data);
// the remote server can now use unserialize($data) to re-construct the user object
?>
If you want to communicate a PHP variable (array, class, string, etc) to another script/a database/write it in a file, you serialize it. Suppose you have a little script that you want to run multiple times, and you need a place to keep some data between script runs. Here is a sketch of what you do:
if(file_exists($thefile)) {
$data = unserialize(readfile($thefile));
} else {
$data = array(); // or anything
}
// do something with data
$f = fopen($thefile);
fwrite($f, serialize($data));
fclose($f)
You can store a PHP structure in a file, session or even database. I use it for caching query results in a file or in memcache.

Categories