如何管理空IN sql查询? [英] How to manage empty IN sql query?

查看:124
本文介绍了如何管理空IN sql查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ids = array(1,2,3);
$in = implode(',',$ids);

$query = "SELECT * FROM user where user_id IN ($in) ";

查询没有问题.但是当$ids为空数组$ids = array();

Query works no problem. But when $ids is empty array $ids = array();

我正确地得到了sql查询错误,因为SELECT * FROM user where user_id IN ()不是有效的查询.

I got sql query error rightly so because SELECT * FROM user where user_id IN () is not a valid query .

如何在不检查空数组的情况下避免这种情况,即使查询无论如何都可以运行?

How can I avoid such situation without checking for empty array i.e making query run no matter what ?

推荐答案

管理此问题的最佳方法是:

Best way to manage this is:

$in = implode("','",$ids); // generate like 1','2
$query = "SELECT * FROM user where user_id IN ('$in') "; //  if has  1','2 surrond it with quote make it IN('1','2') and if empty than IN('')

这可以使您免于if/else结构和其他所有事情

This saves you from if/else structure and everything else

这篇关于如何管理空IN sql查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆