If you want store a php array on you database you can try with json_encode
or serialize
, and when you would need retrive data from you database, you can use json_decode
or unserialize
.
Using JSON
Examples(store as json):
$myArray = array('name' => 'Jack', 'lastname' => 'Smith', 24);
$toStore = json_encode($myArray); // return a string: {"name":"Jack","lastname":"Smith","0":24}
mysqli_query($link,
'INSERT INTO myTable (data)
VALUES ("' . mysqli_real_escape_string($link, $toStore) . '")'
);
Examples(retrieved from json):
$query = mysqli_query($link, 'SELECT FROM MyTable WHERE id = ...');
$row = mysqli_fetch_assoc($query);
$row = json_decode($row); // return a array: array('name' => 'Jack', 'lastname' => 'Smith', 24)
Using serialize
Example(store serialized):
$myArray = array('name' => 'Jack', 'lastname' => 'Smith', 24);
$toStore = serialize($myArray); // return a string: a:3:{s:4:"name";s:4:"Jack";s:8:"lastname";s:5:"Smith";i:0;i:24;}
mysqli_query($link,
'INSERT INTO myTable (data)
VALUES ("' . mysqli_real_escape_string($link, $toStore) . '")'
);
Examples(retrieve serialized):
$query = mysqli_query($link, 'SELECT FROM MyTable WHERE id = ...');
$row = mysqli_fetch_assoc($query);
$row = unserialize($row); // return a array: array('name' => 'Jack', 'lastname' => 'Smith', 24)
After :
if you need access to you data from converted array, you can call like:
$row['name'] // return "Jack"
Another ways
Regexp:
You can try use regexp, but this not the best way because sometime is too slow to process data, and maybe, if you don't know security aspects, this definitely not is the best way.
Tokenizer:
You can try create you own token processor, like template engine, but this is the most large way...
Learn more about the functions:
Pros:
- Support multiple data-types: multidimentional
array
, object
,
integer
, float
, string
, and many more data except resource
.
- Native support for
serialize
and unserialize
since PHP4.
- Native support for
json_encode
and json_decode
since PHP 5.2.0
- Fast and secure encode and decode.