WordPress SQL问题未返回正确的重新设置

时间:2016-01-29 作者:hosker

因此,我一直在研究一个涉及wordpress中的users和usermeta表的SQL查询。我没有得到正确的结果。我编写了以下查询

SELECT 
    * 
FROM 
    IL9_users 
LEFT JOIN 
    ( 
    SELECT 
        user_id, 
        MAX(case when meta_key = \'first_name\' then meta_value end) first_name, 
        MAX(case when meta_key = \'last_name\' then meta_value end) last_name
    FROM 
        IL9_usermeta 
    ) AS um 
ON 
    IL9_users.ID = um.user_id
此代码返回除first\\u name和last\\u name的正确值之外的所有结果。返回的第一个值不正确,但至少返回了该值。所有其他值均为null。有人对此有什么见解吗?

2 个回复
SO网友:hosker

以下是我以代码形式给出的答案:

<?php

// Customer Details

$args = array(
\'blog_id\'      => $GLOBALS[\'blog_id\'],
\'role\'         => \'customer\',
\'meta_key\'     => \'last_name\',
\'meta_value\'   => \'\',
\'meta_compare\' => \'\',
\'meta_query\'   => array(),
\'date_query\'   => array(),        
\'include\'      => array(),
\'exclude\'      => array(),
\'orderby\'      => \'last_name\',
\'order\'        => \'ASC\',
\'offset\'       => \'\',
\'search\'       => \'\',
\'number\'       => \'\',
\'count_total\'  => false,
\'fields\'       => \'all\',
\'who\'          => \'\'
);


$bowlers = get_users( $args );

global $wpdb;

$games_left = $wpdb->get_results("SELECT id, user_id, sum(total_games) AS total_games, sum(games_played) AS games_played FROM `bowling_games` GROUP BY user_id");


?>


<div class="col-xs-12 col-sm-4">
    <h2>Users with 0 Games left</h2>
    <button><a href="" title="">Send Reminder to All</a></button>

    <?php

        foreach ( $games_left as $game_left ) {

            $total_games = $game_left->total_games;
            $games_played = $game_left->games_played;
            $user_id = $game_left->user_id;


            foreach ( $bowlers as $bowler ) {

                if ( $user_id == $bowler->ID ) {


            if ( ( $total_games - $games_played ) == 0 ) { ?>

                <p><?php echo "User ID: " . $user_id . " Name: " . $bowler->first_name . " " . $bowler->last_name . " Email: " . $bowler->user_email  . " Games Left: " . ( $total_games - $games_played ); ?></p>

        <?php       
            }}

        }
        }


    ?>





</div>

SO网友:AjayShanker

WordPress定义了一个名为wpdb的类,该类包含一组用于与数据库交互的函数。

首先初始化一个全局对象变量,$wpdb,它是在/wp includes/wp db中定义的wpdb类的实例化。php。

<?php
    require_once( \'../../../wp-config.php\' );
    global $wpdb;

if ( is_user_logged_in() ) {
    $current_user = wp_get_current_user();
    $ID = $current_user->ID;
    $data = $wpdb->get_results("SELECT * FROM `wp_usermeta` WHERE `user_id` = ".$ID);
    // Where $ID current user id and you can get it by wp_get_current_user() function    
        foreach($data as $k=>$v){
            if($data[$k]->meta_key == \'wp_capabilities\'){
                $roles = unserialize($data[$k]->meta_value);
                foreach($roles as $key => $val){
                    echo "Key: ".$key."--"."Value: ".$val;
                    echo "<br />";
                }
            }
        }
    }
?>