计算特定日期在表中的次数

时间:2015-01-31 17:26:43

标签: php mysql count

我正在尝试编写一个sql查询,该查询将检查一个名为holidays的表,以查找发生超过3次的任何日期。

E.g

  • 31/01/2015
  • 31/01/2015

将返回值2。

这是我到目前为止所得到的,但它没有做任何事情。

function dateCheck($date){

    $date = $date;
    $strSQL = "SELECT `date`, count(*) from `holidays` WHERE `date`= '$date'";
    $query = mysql_query($strSQL);
    return $query;

}

3 个答案:

答案 0 :(得分:1)

    SELECT `date`, count(`date`) as cnt 
    from `holidays` 
    where `date` = '2015-01-01'
    group by `date`
    having count(`date`)  > =3
    order by `date`

答案 1 :(得分:0)

因此,您需要调整查询,然后再获取结果:

function dateCheck($date){
    $strSQL = 'SELECT `date`, count(`date`) as nb_occurrences from `holidays`'
        . " WHERE `date` =  '%s'"
        . ' GROUP BY `date`';

    // use sprintf to inject the escaped string into the SQL, then
    // execute the SQL
    $result = mysql_query(sprintf($strSQL, mysql_real_escape_string($date)));

    // get the result from our aliased column and return it
    if (($row = mysql_fetch_assoc($result))) {
        return (integer) $row['nb_occurrences'];
    } else {
        return 0;
    }
}

现在已经完成了所有这些,你真的不应该使用mysql_*函数。您应该使用mysqliPDO,因为ext/mysql已被弃用。

答案 2 :(得分:0)

尽可能保持与您的代码尽可能接近,但考虑到mysqli和sql注入这里是一个可能更好的修订版本。

function mysqliConnect(  $host, $user, $password, $database ) {

    $mysqli = new mysqli( $host, $user, $password, $database );

    if( mysqli_connect_error() ) {
        die( 'Connect error (' . mysqli_connect_errno() . ')' . mysqli_connect_error() );
    }
    return $mysqli;
}



function dateCheck( $date, $dbConnection ) {

    $date = $date;
    $dbConnection = $dbConnection;
    $count = 0;

    // create prepared statement
    if( $stmt = $dbConnection->prepare( "SELECT `date`, COUNT(*) FROM `holidays` WHERE `date` =?" ) ) {

        // bind params for markers
        $stmt->bind_param( 's', $date );

        // execute query
        $stmt->execute();

        // bind result variables (since you made two columns with your SELECT above)
        $stmt->bind_result( $date, $count);

        // fetch value
        $stmt->fetch();

        // close statment
        $stmt->close();

        // close connection
        $dbConnection->close();
    }

    return (int)$count;
}

$connection = mySqliConnect( 'yourhost', 'username', 'password', 'database' );
$count = dateCheck( 'yourDate', $connection );

然后,您可以在代码中使用$ count变量来检查数字并采取相应的行动。