嵌套的foreach并检查更新/插入查询或删除查询是否有序?

时间:2014-09-30 11:45:09

标签: php mysql nested

好的,这是一个嵌套foreach的函数,我想检查是否需要删除或更新/插入键值对。但是这个不起作用,也许你可以看到我哪里出错了

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 OF 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;
    }

0 个答案:

没有答案