php - 如何使用 LIKE 运算符搜索一个月中的日期?

标签 php mysql sql-like

我有以下数据库结构,我想从特定用户和月份中选择所有内容。然而,它确实会返回特定的用户数据,但会返回所有月份。
我在此示例中选择的月份是 2014-02 或 2014 年 2 月

date       |user      | some more data |
----------------------------------------
2014-01-20 |user1     | more data      | //will not be skipped
2014-02-01 |user1     | more data      |
2014-02-01 |user2     | more data      | //will be skipped
2014-02-02 |user1     | more data      |
2014-05-02 |user1     | more data      | //will not be skipped

我通过准备好的语句函数调用以下查询。 LIKE 运算符似乎不起作用。

$query = "SELECT * FROM table1 WHERE user = ? AND date LIKE ?"
$user = "user1";     //These 2 actually come from user input so:
$date = "2014-02%";  //$user = $username; $date = $y."-".$m."%";
//function that runs the prepared statement (simplified)
//this function works for all other queries.
$result = $database->runQuery($query, array($user, $date));
while($row = mysqli_fetch_array($result){
    echo $row['date'];
    echo $row['user'];
    echo $row['some more data'];
    echo "<br>";
}

这打印

2014-01-20 user1 more data //this line should not be printed but it does.
2014-02-01 user1 more data
2014-02-02 user1 more data
2014-05-02 user1 more data //also should not be printed.

所以我的问题是我对 LIKE 运算符做错了什么?

我的实际查询。

//The system holds phone call data.
//dcontext is a variable that decides in which column the user is found.
//in case of dcontext = outgoing calls
//clid = username + extensions
//src = users phone number
//dst = to phone number (this can be extension from another user in the system)
//which wont be registered double in this case.

//when dcontext = incomming calls
//clid and src = the caller ID/phone number from the person calling.
//dst  = the users phone number.

//when dcontext = internal call transfer
//clid = username + extension
//src = users phone number
//dst = transfered number

"SELECT * FROM table WHERE 
(dcontext = ? AND (clid = ? OR src = ? OR dst = ? OR dst = ?)) OR 
(dcontext = ? AND dst = ?) OR 
(dcontext = ? AND (clid = ? OR src = ?)) AND 
date LIKE ?" 

date type = DateTime 

最佳答案

不要使用like。使用 WHERE user = ?和年(日期)=?和 month(date) = ?,假设 date 是 Date 或 DateType 类型,而不是 varchar。

关于php - 如何使用 LIKE 运算符搜索一个月中的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23989933/

相关文章:

Mysql 多个 LIKE 不起作用

php - 从字符串中获取符号列表

php - 这种方法会保护我的数据库不被修改吗?

mysql - 2 个表中行之间的 SQL 平均值

mysql - 创建多个虚拟变量列是检索数据的有效方法吗?

mysql - 将月初至今与上个月同期 MySQL 进行比较

PHP fatal error : Using $this when not in object context

javascript - PHP数组传递给js时出错

mysql - 复杂的子查询 - 这可能吗?

sql - 如何在 LIKE 语句中连接 % 和列名