0

I have an array inside this variable:

$myArray;

Then I'm inserting it into the database where I have a text field:

mysqli_query($con,"INSERT INTO myTable (thetextfield) VALUES ('$myArray')");

The problem is that I've looked in the table content and it just says "Array" (without the quotes).

Is there not a way to insert the array as it is or separate them by commas and insert them?

2
  • 1
    Often a bad idea.... but serialize() on insert and unserialize() on read
    – Mark Baker
    Commented Aug 27, 2014 at 8:56
  • implode(',',$myArray) Commented Aug 27, 2014 at 8:56

4 Answers 4

6

You can use implode to insert a divisor, like:

$arrayString = implode(",", $myArray);

But if a string containing a , is in $myArray this could cause unexpected results while converting back to an array, because you would suddenly have one more array item. (To convert it back you can use explode)

You can also use json_encode to encode the array to JSON.

$arrayString = json_encode($myArray);

which is much safer. (To decode back to an array use json_decode)

And of course you can just serialize the PHP array:

$arrayString = serialize($myArray);

The con of this option is that the output string can only be read by PHP, unlike JSON which is widely supported. (unerialize can be used to convert the string back to an array)

1

I will suggest you to use serialize your array before saving it and unserialize it again after retrieving from db,

"INSERT INTO myTable (thetextfield) VALUES ('".serialize($myArray)."')"

If you want to save it comma separated use implode function to achieve that,

"INSERT INTO myTable (thetextfield) VALUES ('".implode (", ", $myArray)."')"
1

Use implode

$newString = implode(",", $myArray);
"INSERT INTO myTable (thetextfield) VALUES ('$newString')"
0

You can not insert a array directly to mysql as mysql will not recognize it.

You need to convert the array either using php implode or you can use serialize or json_encode with php..In that way it will be easier for you to retrieve array data as well.

2
  • You should've just upvoted the answer that's the same as your idea rather than giving another answer. Commented Aug 27, 2014 at 9:03
  • yes, actually when I was answering the question there was no answer for this question. Commented Aug 27, 2014 at 9:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.