0

I have created a custom Wordpress form and I am working on inserting the submissions into a custom table in my database. Passing single fields into the table is working great, but I also have an array I need to insert as well. I created a LONGTEXT field, but when I try to insert the array into the field nothing is getting inserted.

Here is my $wpdb insert code:

$name = $_POST['name'] ?? '';
$products = $_POST['products'] ?? '';

global $wpdb;
$tablename = $wpdb->prefix . 'orders';

$wpdb->insert($tablename, 
    array(
        'name' => $name,
        'products' => $products
    ),
    array('%s', '%s')
);

The $products variable is the array. How can I make it so that the array gets passed in the products field of my custom table? Also, is LONGTEXT the correct field type?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
user13286
  • 3,027
  • 9
  • 45
  • 100
  • 1
    There's several ways, but only two are "decent": One, use `serialize`. What's nice about this is that WP uses serialize, and has a useful function called `maybe_unserialize` that is defensive / smart about unserializing data. **However** - I personally DO NOT like serialize, as it is fairly brittle and not readable. Instead, I'd recommend using `json_encode`: `$string = json_encode( array('name' => $name, 'products' => $products));` - then insert `$string` into your `LONGTEXT` field. – random_user_name Sep 25 '19 at 15:41
  • @cale_b Thanks! `json_encode` worked great. – user13286 Sep 25 '19 at 15:44
  • 1
    **TO BE CLEAR** - the answers in the duplicate link _are not great_. Please read the comment here about serialize / json_encode, which would be preferable to many of the other answers at the duplicate... – random_user_name Sep 25 '19 at 15:47

0 Answers0