rwkiii rwkiii - 3 months ago 26
MySQL Question

Unable saving an associative array using add_post_meta() function

I need to run an encryption function on each member of an associative array prior to it being saved to

wp_postmeta
table. My form allows dynamic add/delete of rows. I've been trying to get this to work using
array_walk()
.

This is how the form is configured:

<input type="text" id="z_my_data[][username]" name="z_my_data[0][username]">
<input type="text" id="z_my_data[][password]" name="z_my_data[0][password]">


This is ran on the 'save_post` action:

// Save encrypted data to post meta
if (isset($_POST['z_my_data'])) {

// Get posted form variables
$my_data = $_POST['z_my_data'];

// Encrypt each member of each row
for ($i = 0; $i < count($my_data); $i++) {
$cryptKey = $this->cryptKey;
array_walk($my_data[strval($i)], create_function('&$val', 'global $cryptKey; $val = Crypto::encrypt($val, $cryptKey);'));
}

if ( ! add_post_meta( $post_id, '_my_data', $my_data, true ) ) {
update_post_meta( $post_id, '_my_data', $my_data);
}

} else {
delete_post_meta( $post_id, '_my_data' );
}


I can see that the data is being encrypted. Here is a
print_r($my_data)
after the
for
loop:

Array
(
[0] => Array
(
[username] => ®ØåÛâÏ0…"ë°?mˤÙ
[password] => xSFç„L¶·3z˜'J0ÖRÅÎj
)

)


But the post meta key is not created and no error is generated. The meta key doesn't exist in the postmeta table, yet
add_post_meta()
returns false and the key/value is never added.

Does anyone see what I'm doing wrong?

I'm not sure how to tell, but I think the [0] is a named key and not an index key. I say that because I can create more than one and delete the [0] element and the single element remaining still shows [1] using
print_r
.

Answer

In your if ( ! add_post_meta( $post_id, '_my_data', $my_data, true ) ) { you are using add_post_meta() function and last argument is set to true.
It should be false instead, because you are inserting an array and NOT a string.
For this reason your if statement is not working properly.

Instead, your code should be (as add_post_meta last argument default value is false):

if ( ! add_post_meta( $post_id, '_my_data', $my_data ) ) { 
    update_post_meta( $post_id, '_my_data', $my_data );
}

Alternatively, you could also use this:

if ( ( !empty( get_post_meta( $post_id, '_my_data' ) ) ) { 
    update_post_meta( $post_id, '_my_data', $my_data );
}

References: