这是我得到的错误
SQLSTATE [42000]:语法错误或访问冲突:1064您的SQL语法有一个错误;请参见语法。请查看与您的MariaDB服务器版本相对应的手册,以在“ anish123@gmail.com”附近使用正确的语法。第2行中的GROUP BY email,date'(SQL:SELECT email,date,min(time)AS checkin,max(time)AS checkout,(((TIME_TO_SEC(TIMEDIFF(max(time),min(time))))/ 60 )/ 60)区别↵来自个人资料WHERE'。1 = 1和类似'anish123@gmail.com'的电子邮件。'GROUP BY电子邮件,日期)“
我正在尝试根据提供的电子邮件和单击按钮来过滤数据。第一个查询运行正常,但是当我尝试在第二个查询中使用相同的where条件时出现错误。
$post = $request->all();
$email = $request->input('email');
$cond = ' 1=1 ';
if(!empty($post['email'])){
$cond .= " and email like '".$post['email']."'";
}
$qry = 'SELECT User_id, email, status, date, time FROM profile WHERE '.$cond.' ';
$data = DB::select($qry);
$sql=" SELECT email, date, min(time) AS checkedin, max(time) AS checkedout,( (TIME_TO_SEC(TIMEDIFF(max(time), min(time))) / 60) / 60) difference
FROM profile WHERE '.$cond.' GROUP BY email, date";
$previousdata = DB::select($sql);
答案 0 :(得分:1)
您为$sql
使用了错误的字符串连接:
$sql=" SELECT email, date, min(time) AS checkedin, max(time) AS checkedout,( (TIME_TO_SEC(TIMEDIFF(max(time), min(time))) / 60) / 60) difference
FROM profile WHERE " . $cond . " GROUP BY email, date";
使用原始SQL,您的查询将容易受到SQL注入的攻击。 Read more about this problem。
从技术上讲,您可以将Laravels query builder用于两个语句。
$conditions = [];
if ($email) {
$conditions[] = ['email', 'like', $email];
}
$profile = DB::table('profile')
->select('user_id', 'email', 'status', 'date', 'time')
->where($conditions)
->get();
$previousData = DB::table('profile')
->select('email', 'date', DB:raw('min(time) checkedin'), DB:raw('max(time) checkedout'), DB::raw('((TIME_TO_SEC(TIMEDIFF(max(time), min(time))) / 60) / 60) difference'))
->where($conditions)
->groupBy('email', 'date')
->get();
答案 1 :(得分:1)
我已经在上面的右侧编辑了代码。错误是由于字符串串联
$sql="SELECT email, date, min(time) AS checkedin, max(time) AS checkedout,( (TIME_TO_SEC(TIMEDIFF(max(time), min(time))) / 60) / 60) difference
FROM profile WHERE".$cond. "GROUP BY email, date";