Build SQL Select a better way ? (Oracle)
i hav开发者_开发问答e the following code part in one of my classes:
$l = new Location();
$result = $l->getLocIdsbyCity($city); // returns csv
$ids = explode(',', $result);
$where = 'LOC_ID = ' . $ids[0];
unset($ids[0]);
foreach ($ids as $id) {
$where .= ' OR LOC_ID = ' . $id;
}
$select->where($where);
Is there an more "elegant" way to build the select stmt? I need all records with one of the provided ids..
Assuming your csv
is injection safe (contains trusted values and no user-provided input):
$l = new Location();
$result = $l->getLocIdsbyCity($city); // returns csv
$where = "LOC_ID IN ($result)";
$select->where($where);
If it's not, you should explode it, mysql_real_escape_string
each value and implode back.
You can use the in
operator to form a condition like:
where LOC_ID in (1,2,3,4,5)
If you are sure that $result
can't contain anything harmful, you should be able to use it directly without having to split it and loop.
精彩评论