68

My homework has a problem for example there is a category array $cat=array('1','4','5','7'); now i need to select products from db based on the category that is

SELECT * FROM products WHERE catid='1'
SELECT * FROM products WHERE catid='4'
SELECT * FROM products WHERE catid='5'
SELECT * FROM products WHERE catid='7'

Is it possible to do this in a single query? as the final results of the four queries will be combined.

3 Answers 3

124
SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')
Sign up to request clarification or add additional context in comments.

2 Comments

is this query return data in this order only? like the first record is with id=1, second of 2 and so on?
To ensure sorting, you have to add a ORDER BY to the query. SELECT * FROM products WHERE catid IN ('1', '2', '3', '4') ORDER BY catid
21
// array of $ids that you need to select
$ids = array('1', '2', '3', '4', '5', '6', '7', '8');

// create sql part for IN condition by imploding comma after each id
$in = '(' . implode(',', $ids) .')';

// create sql
$sql = 'SELECT * FROM products WHERE catid IN ' . $in;

// see what you get
var_dump($sql);

Update: (a short version and update missing comma)

$ids = array('1','2','3','4');
$sql = 'SELECT * FROM products WHERE catid IN (' . implode(',', $ids) . ')';

2 Comments

your answer would be useful for very huge amount of values in an array/list
@elliotching yes, you just must have an array with ids, everything else is generated by 1-2 lines of script, here is the long version just for readability and for comments on what each line do
-3
$SQL_Part="("
$i=0;
while ($i<length($cat)-1)
{
   $SQL_Part+=$cat[i]+",";
}
$SQL_Part=$SQL_Part+$cat[$i+1]+")"

$SQL="SELECT * FROM products WHERE catid IN "+$SQL_Part;

It's more generic and will fit for any array!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.