Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting an array into a mysql database column

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.

like image 945
user3241754 Avatar asked May 31 '26 09:05

user3241754


2 Answers

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

like image 190
Abhik Chakraborty Avatar answered Jun 02 '26 23:06

Abhik Chakraborty


you can turn the array into a single string with https://www.php.net/function.implode

$comma_separated = implode(",", $array);
like image 28
Joe T Avatar answered Jun 02 '26 22:06

Joe T



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!