简体   繁体   中英

Sort users by age group using PHP and MySQL?

I am trying to set a query that displays all users on my site who are under 25 based on the age which is in my table ptb_stats.user_age . I set an interval of -25 years but it's not working the way I expect. What am I doing wrong?

My function:

function categories_agegroup_under25() {
            global $connection;
            $query = "SELECT *
                        FROM ptb_users, ptb_stats
                        WHERE ptb_users.account_type = \"User\" AND ptb_users.account_status = \"Active\" AND ptb_stats.user_id = ptb_users.id
                        AND ptb_stats.userage >= ADDDATE(CURRENT_DATE(), INTERVAL -25 YEAR)             

                        ORDER BY ptb_stats.user_age DESC
                        LIMIT 0,40";
            $categories_under25_set = mysql_query($query, $connection);
            confirm_query($categories_under25_set);
            return $categories_under25_set;
        }

My php:

<?php
 $dob = $age['user_age'];

function age_from_dob($dob) {


       $date = date_diff(date_create($dob), date_create('now'))->y;  
       return $date;
}

?>
    <?php
        $categories_under25_set = categories_agegroup_under25();
        while ($age = mysql_fetch_array($categories_under25_set)) {
            $date = age_from_dob($age['user_age']);

            echo"
            <div class=\"boxgrid caption\">
            <a href=\"profile.php?id={$age['id']}\"><img width=140px height= 180px src=\"data/photos/{$age['id']}/_default.jpg\"/></a>
            <div class=\"cover boxcaption\">
            <h58> {$age['display_name']}, ".$date."</h58>
            </div>
            </div>";
        }
    ?>

我猜你在找

SUBDATE(CURRENT_DATE(), INTERVAL 25 YEAR)

Is ptb_stats.userage a number or a timestamp? If it is a number than where ptb_stats.userage < 25 will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM