Save array in mysql database - php

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

Related

JSON data handling with mySQL and php

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.

How to store data in db in array form

i want to store my PHP values in db(mysql) in the form of array...
for example
$a=array{10,20,30,40};
i want to store this variable $a in to db in the array form like how it's storing in array using index.
why i want to do this because in future i may have to perform update or delete operation on the array values..
i know that it's possible to do this thing... but i don't know how to implement this..
i searched about this topic but i didn't get proper answer....
Please suggest me how to do this things...
Why don't use json_encode in PHP and store it on your database. It's the best way.
The array will be converted to a string and will be stored.
Retrieve the data and make use of json_decode and then start working as per your needs.
Example:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
OUTPUT: {"a":1,"b":2,"c":3,"d":4,"e":5}
You should create a distinct TABLE to store this kind of data.
Consists of 2 columns, corresponding record ID and the actual data.
So, your record will be looks like
rid value
1 10
1 20
1 30
1 40
2 10
2 40
...
this way you will be able to perform update or delete operation on the array values using conventional SQL routines, as well as selecting data based on the array values.
This is how the things done oin the real world, not in PHP sandbox.
All othe answers here are plainly wrong
I would use serialize/unserialize for this. You can use it like this:
Send to MySQL
<?php
$a = array{10,20,30,40};
$a = serialize($a);
// your code here to send it to the mysql
?>
Get from MySQL
<?php
// your code here to collect it from mysql
$a = unserialize($mysql->str);
?>
The field in the MySQL should be TEXT or VARCHAR.
Regards
BlackBonjour
You can always serialize your array then store the result in a VARCHAR or TEXT field and after fetching you can unserialize the field.

PHP get MySQL database as associative array by row

I have a simple mySQL database table that I am loading into a PHP array. I would like the id column of the mySQL table (which is auto incremented, but I don't think that's relevant) to be the array key for each element of the PHP array, instead of the array being numeric.
Instead of this:
Array(
Array(id=>'1', field1=>someval, field2=>val),
Array(id=>'2', field1=>val, field2=>otherval),
Array(id=>'4', field1=>val, field2=>otherval)
)
I want this:
Array(
1=>Array(field1=>someval, field2=>val),
2=>Array(field1=>val, field2=>otherval),
4=>Array(field1=>val, field2=>otherval)
)
I don't care if id is left in the associative array for each row.
Is there a way to do this without looping through the original mySQL array and using up lots of processing time?
You can do it at the fetch time like this:
$query_ret = mysql_query(...);
$result = array();
while ($row = mysql_fetch_assoc($query_ret)) {
$result[array_shift($row)] = $row;
}
"Is there a way to do this without looping through the original mySQL array and using up lots of processing time?"
I believe the answer to this is no. The best you can do is to try to be as efficient as possible when looping through the array.
If you have PDO, you should definitely see Example #3 from the PDO documentation for fetchall: http://www.php.net/manual/en/pdostatement.fetchall.php#example-1022
Not only is this way more efficient use of your server's memory and processing power... it would also enable you to take advantage of several of PDO's other powerful APIs.

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.

Problems with serialize() and unserialize() - inserting and selecting data PHP MySQL

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.

Categories