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?

Satch3000
  • 47,356
  • 86
  • 216
  • 346

4 Answers4

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)

idmean
  • 14,540
  • 9
  • 54
  • 83
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)."')"
Rikesh
  • 26,156
  • 14
  • 79
  • 87
1

Use implode

$newString = implode(",", $myArray);
"INSERT INTO myTable (thetextfield) VALUES ('$newString')"
arunrc
  • 628
  • 2
  • 14
  • 26
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.