I am trying to insert values from a multi select drop down in a form to a mysql db column. For example: The drop down would have one or more choices chosen then when the form is posted it would insert the data into one column in a mysql db. I'm stuck at how to insert the data.
If you want to insert in single row then you can use implode() to generate comma separated data, or you can do json_encode() and add to your colum.
Say you get the data as
$data = array("one", "two", "tree");
// output one, two, three
$insert_data = implode(",", $data);
or
$insert_data = json_encode($data);
Thats for inserting data in single column. While retrieving you can do explode() or json_decode() to get the return data and can use them in the multi-select again.
If you want one row for each item then just loop through the array and add them
you can turn the array into a single string with http://us1.php.net/function.implode
$comma_separated = implode(",", $array);
set the type of the column to string, then use the function serialize($array) to convert the array into a string. When you want to get the string back to an array, use unserialize($string)
A couple of things to think about:
If there is a one to many relationship - it shouldn't be in one column, look into multiple tables and changing your database structure.
If you really want to pass in an array you will need to convert it to string using the php built in function implode, then using the built in function explode to retrieve the column from the db
$arr = array('val1','val2');
$string = implode(',',$arr);
//Do db insert
//Do db retrieve
$arr = explode(',',$string);
http://php.net/function.implode
Related
I was used implode function for an array to insert the value into DB.
$day1=implode(',',$day);
echo "day:".$day1;
$day have a value of array like {100,100}; now i change this like 100,100 string to insert into the table. because I can't store array directly into the table.if any option instead of implode() to load the array into DB please post that.
else help me which datatype is used to store in DB . i cann't use int because of commas.
Under the assumption you are using MySQl, you should be utilizing the TEXT data type, because this data type offers no assumptions on what size your insert will be. Now, of course if you want to calculate a fixed length, feel free to use varchar, but because of the unknown width of your numbers, you would have to overallocate regardless.
https://dev.mysql.com/doc/refman/5.5/en/blob.html
Storing it as a string with numbers delimited by a comma is an adequate storage format, and should work fine, as you are dealing with numbers there would be no conflict when retrieving the data and then exploding the value back into an array using the same comma delimiter.
The implode() returns the array items concatenated to a single string (http://php.net/manual/en/function.implode.php).
Your database field needs to be of a text type (char, varchar, text) to store the value.
In this situation you have to convert array into json and store in db.
ex:
$data=("a","b","c");
$json_encode=json_encode($data);
then after retrieved from db convert back to array.
ex:
$json_decode=json_decode($data,true);
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
// Empty string when using an empty array:
var_dump(implode('hello', array())); // string(0) ""
I know there is mysql_fetch_assoc which puts all data from a row into an array. Is there something equivalent for putting all data in a column into an array? e.g. a list of title ID's?
GROUP_CONCAT and explode() is probably what you're looking for as it can get everything in one row. You can group all of the values with a comma using GROUP_CONCAT and then populate the array using explode().
Your SQL would contain this:
SELECT GROUP_CONCAT(column_name SEPARATOR ',') AS col
And your PHP would create the array like this (after performing the query):
$col_array = explode(',' $row['col']);
Here's my suggestion:
$arr = array();
while ($row = mysql_fetch_assoc($result)) {
$arr[] = $row['id']; // replace id with your column name.
}
var_dump($arr);
If you're able to use external libraries, it may be worth looking into the Zend database library. Zend_Db provides a function called fetchCol where it will return an array without having to write any additional code.
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
I have this serialize data in my mySQL database
a:4:{i:0;s:7:"bvl.png";i:1;s:8:"ccop.jpg";i:2;s:11:"reyborn.png";i:3;s:13:"swopgroup.jpg";}
How can I update this data, for example I want to delete ccop.jpg?
Do not store serialized data in database.
Create a linked table consists of main_id and picture and store your image names in it.
So, you will have distinct access to them.
You have to fetch the value from the database, unserialize it, remove the element, serialize it and save again.
$remove = "ccop.jpg";
//
// get the string from the database
//
$arr = unserialize($str);
foreach($arr as $key => $value)
if ($value == $remove) unset($arr[$key]);
$str = serialize($arr);
//
// save the string back to the database
//
Instead of saving serialized list of values, it's better to have a normalized database and just do a simple DELETE FROM images WHERE object_id = ....
Ideally you need to
extract it
deserialize it
modify it
serialize it
write it back to the database.
Since you are storing it in a VARCHAR field and it is a PHP serialized array you would want to pull it out of the database unserialize and then re-update the field. You shouldn't look to MySQL to modify PHP specific information because well ... that's not what it is made for.
I have a MySQL field which stores an array with 3 values:
array(item1=>1123, item2=>5454, item3=>23432)
How can I query the database with PHP so that I get only distinct values of item2 and then arrange those results by the values of item3?
A lot more information is needed - like, how your database is structured.
Look into the DISTINCT() function and the ORDER BY clause of SQL
It much easier to store your array into text and something you can separate later. Using php you can do this. I'll try to work with your data here into something you can use. says you have the field items. If instead you had an array such as.
$items = array(1123,5454,23432);
You can then implode it with a symbol such as:
$items = implode('|',$items);
and then store this in the database under a fields such as items that would look like this:
1123|5454|23432
Then when you want to grab the data you just need to explode it with the same symbol:
$items = explode('|',$row['items']);
and you are back with your dataset:
$items[0] = 1123
$items[1] = 5454
$items[2] = 23432
and then can access the second item by grabbing element one of the array:
$items[1]
Hopefully that gives you a better understanding of it.