Chaya Cooper
Chaya Cooper

Reputation: 2530

How can I insert an array into one row?

The following code works for inserting an array from a form, but it inserts each value into it's own row. How can I insert an array into one row?

<?php 
require_once('config.php'); 
require_once('open_db.php');
$palette=$_POST['colors_palette'];
while (list ($key,$val) = @each ($palette)) {
}
For ($i=0; $i<sizeof($palette);$i++) {
$query="INSERT INTO style_test1 (colors_palette) VALUES ('".$palette[$i]."')";
Mysql_query($query) or die(mysql_error());
}
Echo "Record is inserted";
?>

<form method="post" action="insert_array.php" >
<input type="checkbox" name="colors_palette[]" value="jewel" />                
<input type="checkbox" name="colors_palette[]" value="bright" />                     
<input type="checkbox" name="colors_palette[]" value="soft" /> 
<input type="checkbox" name="colors_palette[]" value="earth" />
<input type="submit" name="Submit" value="Submit" />
</form>

Upvotes: 0

Views: 2202

Answers (3)

Omesh
Omesh

Reputation: 29101

to convert array into comma separated variables use implode function in PHP as:

$query="INSERT INTO style_test1 (colors_palette) VALUES ('".implode(',',$palette)."')";

EDIT: try this code:

<?php 
 require_once('config.php'); 
 require_once('open_db.php');

 $palette=$_POST['colors_palette'];

 $query="INSERT INTO style_test1 (colors_palette) VALUES ('".implode(',',$palette)."')";
 mysql_query($query) or die(mysql_error());

 echo "Record is inserted";
?>

Upvotes: 1

pat34515
pat34515

Reputation: 1979

To insert as a string:

<?php 
 require_once('config.php'); 
 require_once('open_db.php');

 $palette=$_POST['colors_palette'];

 $query="INSERT INTO style_test1 (colors_palette) VALUES ('". serialize($palette) ."')";
 mysql_query($query) or die(mysql_error());

 echo "Record is inserted";
?>

You could then unserialize to the get the data back as an array or object.

A better way to do it though, is to insert is as a JSON formatted string.

$query="INSERT INTO style_test1 (colors_palette) VALUES ('". json_encode($palette). "')";

Then you can use json_decode to decode it back to an array.

Implode:

$pal   = implode(',', $palette);
$query = "INSERT INTO style_test1 (colors_palette) VALUES ('".$pal."')";

Upvotes: 3

Jo&#227;o Mosmann
Jo&#227;o Mosmann

Reputation: 2902

You can use the PHP function

serialize($myArray);

This function transform a array into a string. So you can insert in a row field.

And use unserialize on the string to get a array.

You can too implode the array to get a string

$string = implode(',',$myArray);

Upvotes: 1

Related Questions