I want to return records where a id field is in a php array. Usually I would do something like this:
$ids = array(1,2,3,4)
$query = "SELECT * FROM table WHERE statusId IN (" . implode(',',$ids) . ")";
However, if the $ids
array happens to be empty, I get a error from mysql because of the empty parentheses. I can accomplish my goal using a subquery like this:
$query = "SELECT * FROM table WHERE statusId IN (SELECT statusId FROM statuses WHERE /* some conditions */)";
If the subquery is empty, then it will just return an empty record set without an error. I don't want to use the subquery because I already have the ids in the php variable.
Is there a way to write the first query so it doesn't return an error if the php array is empty? I know I can just write a conditional statement and just not run the query if the php array is empty. But for style reasons, I just want to see if there is a way to write the query that returns a empty set if the php array is empty.
You would better check if the array is empty. Just write:
if ( empty($ids) ) {
//Don't run query
}
$ids = array(1,2,3,4)
$idClause = !empty($ids) ? implode(',',$ids) : 'NULL';
$query = "SELECT * FROM table WHERE statusId IN (" . $idClause . ")";
try doing a ternary
$ids = array(1,2,3,4)
$query = !empty($ids) ? "SELECT * FROM table WHERE statusId IN (" . implode(',',$ids) . ")" : "SELECT * FROM table WHERE statusId IN (SELECT statusId FROM statuses WHERE /* some conditions */)";
;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.