我添加了一个看起来像usermeta表的自定义db表,只存储了一些键值对。但现在我被以下逻辑所束缚
如果用户有键,则使用更新查询,否则使用插入查询。如果键不再存在,则删除键值行。现在,对于a部分,我有此功能,但似乎跳过了最后一个键并始终插入。
`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;
}`
我的循环哪里出错了?
还是应该删除所有键值对并使用插入查询?我能想到的一个缺点是meta\\u id table字段是自动递增的,可能会变得非常难看
SO网友:alex
好的,这是我修改过的函数,但这一个根本不起作用,但也许你可以看到我是否出错
function insertUserShoppingMetaData($params) {
global $wpdb;
$shopping_meta_table = \'wp_shopping_metavalues\';
$wp_user_id = $params[\'wp_user_id\'];
$checkKeyValues = $wpdb->get_results("SELECT meta_shopping_key FROM $shopping_meta_table WHERE wp_user_id = \'$wp_user_id\'");
//print_r($checkKeyValues);
foreach ($params as $key => $val) {
foreach($checkKeyValues as $check){
//UPDATE OR INSERT
if (($check->meta_shopping_key == $key) AND ($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_key\' => $key, \'meta_shopping_value\' => $val), $shopping_meta_where) . \'<br/>\';
} else {//KEY IS NEW
$return = $wpdb->insert($shopping_meta_table, $shopping_meta_values) . \'<br/>\';
}
}//.end $key
else {
//KEY IS NOT SELECTED ANYMORE SO DELETE key value pair row
$qdel = $wpdb->delete($shopping_meta_table,array(\'wp_user_id\'=>$id));
$return = \'Deleted: \'.$qdel;
}//.end else {
}//.end foreach checkKeyValue
}//.end each
echo \'Test return: \' . $return;
}