如何通过MySQL将count()组保存到php变量中

时间:2018-12-29 19:30:09

标签: php mysql

我需要将user_posted_to的count(activity_type)组保存到mysql查询的变量中

$query = "
        SELECT user_posted_to, COUNT(*)
       FROM activity_log_table 
       WHERE 
           post_type = 'discussion' 
          AND activity_type = 'Like' ";
$query .= "AND activity_timestamp >= CURRENT_DATE - INTERVAL 7 DAY AND activity_type <= CURRENT_DATE ";
$query .= "GROUP BY user_posted_to ORDER BY activity_timestamp DESC LIMIT 25";
$result = mysqli_query($connection, $query);



 while ($row = mysqli_fetch_assoc($result)) {
            $user_posted_to = (int)$row['user_posted_to'];
            $timestamp = time();
            // I need to insert the count into this table for number_assert
            $query2 = "INSERT INTO top_weekly (user_id, number_assert, timestamp) VALUES ($user_posted_to, $timestamp)";
            $result2 = mysqli_query($connection, $query2);
            $confirm_query2 = confirm_query($result2);

        if($confirm_query2) {
            echo "success query 2";
        } else {
            echo "failed query 2";
        }
    }

我希望将count()组保存到一个php变量中,以便稍后在页面上使用它

2 个答案:

答案 0 :(得分:2)

您想将«COUNT(*)»别名为其他名称,例如«cnt»。然后,您可以在提取后按名称访问该列,如下所示:

$query = "
    SELECT 
        user_posted_to, 
        COUNT(*) as cnt
    FROM activity_log_table 
    WHERE 
        post_type = 'discussion' 
        AND activity_type = 'Like'
       AND activity_timestamp >= CURRENT_DATE - INTERVAL 7 DAY
        AND activity_type <= CURRENT_DATE
    GROUP BY user_posted_to 
    ORDER BY activity_timestamp DESC 
    LIMIT 25";

$result = mysqli_query($connection, $query);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "user_posted_to: " . $row["user_posted_to"]. " - Count: " . $row["cnt"] . "<br>";
    } 
} else {
    echo "0 results";
}

答案 1 :(得分:1)

在COUNT(*)中添加AS标签,然后您将能够在得到的行中读出该标签。

$query = "SELECT user_posted_to, COUNT(*) AS varCount FROM activity_log_table WHERE post_type = 'discussion' AND activity_type = 'Like' ";

$nummerOfCount = $row['varCount']