php - 查询返回空时出现语法错误或访问冲突

标签 php mysql laravel

如果查询没有返回任何内容,我会收到一些奇怪的错误。我该如何正确处理这个问题?

错误:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1 (SQL: select users.uid, first_name, last_name, IFNULL(files.filename, 'default.jpg') AS avatar, privacy from users left join user_avatars on users.uid = user_avatars.uid left join files on user_avatars.fid = files.fid where users.uid in ())

代码:

$me = User::loggedin();
$contacts = DB::table('contacts')
        ->where('status', 'contact')
        ->where('uid_by', $me)
        ->orWhere('uid_to', $me)
        ->select(
        DB::raw("IF(uid_by = $me, uid_to, uid_by) AS user_id")
        )
            ->paginate(10);

if ($contacts != null) {
    $users_id = array();

    foreach ($contacts as $contact) {
    $users_id[] = $contact->user_id;
}

$data = DB::table('users')
        ->leftJoin('user_avatars', 'users.uid', '=', 'user_avatars.uid')
        ->leftJoin('files', 'user_avatars.fid', '=', 'files.fid')
        ->whereIn('users.uid', $users_id)
            ->select('users.uid', 'first_name', 'last_name', DB::raw('IFNULL(files.filename, \'default.jpg\') AS avatar'), 'privacy')
            ->get();


return Response::json(array('contacts' => $data));          
}

//if no data was returned
return Response::json(array('contacts' => 0));
<小时/>

更新

我尝试添加 die(var_dump($contacts)); 但它返回了很多 laravel 相关对象。

另一方面,如果我添加 ?page=1 那么它会成功返回 2 个联系人。
如果我添加 ?page=2 那么它会给出错误。 (可能是因为没有数据)但我想正确处理这个问题。

最佳答案

你需要在该行周围添加一些逻辑

>whereIn('users.uid', $users_id)

由于您已经链接了调用,因此您不能简单地在该行周围放置一个 if (无论如何它都不会在逻辑上工作。也许这会做到这一点..

if ($users_id){
$data = DB::table('users')
                            ->leftJoin('user_avatars', 'users.uid', '=', 'user_avatars.uid')
                            ->leftJoin('files', 'user_avatars.fid', '=', 'files.fid')
                            ->whereIn('users.uid', $users_id)
                            ->select('users.uid', 'first_name', 'last_name', DB::raw('IFNULL(files.filename, \'default.jpg\') AS avatar'), 'privacy')
                            ->get();
} else {$data = null; /*or empty set however that is defined in your framework*/ }

关于php - 查询返回空时出现语法错误或访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20804675/

相关文章:

php - 时间戳、时区和夏令时

php - 使用 PHP 和 MySQL 的 jQuery 倒计时

php - 我使用 phpmyadmin 更改了我的 WordPress 密码,现在我有一个数据库错误

PHP-HTML 使用 input=text 更新 mysql,其中 POST ['submit' ]

php - 仅 Mysql 原始计数

Laravel @yield 显示带有 HTML 标签的内容

javascript - 鼠标悬停时在固定位置显示图像

mysql - Hibernate session.beginTransaction()调用和Mysql Start Transaction

Php foreach 在时隙间隔中循环,如果间隔空闲则仅返回四分之一时间

php - 拉维尔 5.5 |标签只出现在最后一篇文章中?