I have added a custom db table which looks like usermeta table, just storing some key - value pairs. But now i am stuck with the following logic
- a/ if key exist for a user use an update query else an insert query
- b/ if an key doesn't exist ANYMORE delete the key - value row
Now for part a i have this function, but it looks like the last key is skipped and always inserted.
`function insertUserShoppingMetaData($params) {
global $wpdb;
$shopping_meta_table = 'wp_shopping_metavalues';
$wp_user_id = $_POST['wp_user_id'];
foreach ($params as $key => $val) {
if ($key != "wp_user_id") {
if (is_array($val)) {
$val = json_encode($val);
}
$shopping_meta_values = array(
'wp_user_id' => $wp_user_id,
'meta_shopping_key' => $key,
'meta_shopping_value' => $val
);
$shopping_meta_where = array('meta_shopping_key' => $key, 'wp_user_id' => $wp_user_id);
}
$result = $wpdb->get_results("SELECT * FROM $shopping_meta_table WHERE meta_shopping_key = '".$key."' AND wp_user_id = '$wp_user_id'") ;
if(count($result) > 0){//KEY ALREADY EXISTS FOR USER
$return = $wpdb->update($shopping_meta_table, array('meta_shopping_value' => $val), $shopping_meta_where).'<br/>';
} else {//NEW KEY VALUE SO INSERT
$return = $wpdb->insert($shopping_meta_table, $shopping_meta_values).'<br/>';
}
}
echo 'Test return: ' . $return;
}`
Where does my loop go wrong?
OR should i just delete all key-value pairs and use an insert query? One drawback i can think of is the meta_id table field which is auto-increment and can get really ugly
if ($key != "wp_user_id")
was wrongly set. I had to put it after the update/insert queries. Still have to find a solution for b/ if an key doesn't exist ANYMORE (not selected in the form) delete the key - value row