我正在尝试选择重复日期的计数并输出其数字
$user_curr_id = $_SESSION['user_id'];
$sql = "SELECT COUNT(datum) FROM table_name WHERE user_ids = $user_curr_id";
我不知道该怎么做。
2014-07-23,2014-07-23,2014-07-23 => 3
2014-07-24,2014-07-24 =>2
2014-07-25 => 1
并获取$result = 3,2,1
答案 0 :(得分:2)
我假设你正在照看GROUP BY子句:
$sql = "SELECT datum, COUNT(datum) as cnt
FROM table_name
WHERE user_ids = $user_curr_id
GROUP BY datum
ORDER BY COUNT(datum) DESC;";
如果您的列datum
属于数据类型DATE
。
注意强>
如前所述,您很容易受到sql注入攻击。您应该使用参数化的预准备语句并将输入值绑定到此参数,如:
$sql = "SELECT datum, COUNT(datum) cnt
FROM table_name
WHERE user_ids = ?
GROUP BY datum
ORDER BY COUNT(datum) DESC;";
$result = array();
if ($stmt = $mysqli->prepare($sql)) {
if ($stmt->bind_param('s', $user_curr_id)) {
if($res = $stmt->execute()) {
while ($row = $res->fetch_assoc()) {
$result[] = $row['cnt']; // add the content of field cnt
}
}
}
}
echo implode(',', $result);