tags:

views:

25

answers:

3

I'm trying to get the categories name from each array value from the database and then add the categories name to an array $cat_name, how can I do this using PHP & MySQL?

$array = array(1, 2, 3, 4, 5);

$cat_name = array();
$dbc = mysqli_query($mysqli,"SELECT category 
                 FROM categories 
                 WHERE id = '" . $array . "'"); 


if (!$dbc) {
    print mysqli_error($mysqli);
} else {
    while($row = mysqli_fetch_array($dbc)){
    $cat_name[] = $row['category'];
    }
}
A: 

do it like this:

$dbc = mysqli_query($mysqli,"SELECT category 
                 FROM categories 
                 WHERE id IN (" .implode(",", $array). ")"); 
Vaibhav Gupta
what if my array looks like this `Array ( [0] => 1 [1] => 34 ) `
leftout
what type of id is means interger, alphanum etc. if its numeric then this array can not be applied...and the array must be single dimension otherwise u have to use SELECT query more than one...
Vaibhav Gupta
@Vaibhav Gupta look at the new edit
leftout
ok fine... den u need:$array2=new array();foreach($array as $k=>$v){ $array2[] = $v;}$dbc = mysqli_query($mysqli,"SELECT category FROM categories WHERE id IN (" .implode(",", $array2). ")");
Vaibhav Gupta
A: 
$dbc = mysqli_query($mysqli,"SELECT category 
    FROM categories
    WHERE id IN (" . implode(",", $array) . ")");

However when doing thing make sure your array actually contains only integers or you'll have a nasty SQL injection hole. If your array might contain something else, loop through it escaping all values and enclosing them in quotes before doing this.

Matti Virkkunen
what if my array looks like this `Array ( [0] => 1 [1] => 34 ) `
leftout
@leftout: ...that is an array of integers. Just make sure it's always like that.
Matti Virkkunen
A: 

The code looks good. Am I right to presume that you are getting an error each time? I don't think your SQL syntax is right. I use 'WHERE id IN('.implode($array,',').')'. Not sure whether this is your question...

EDIT: I have the slight suspicion that you could also do away with your loop and instead simply issue a second fetch for the 'categories' column.

Ollie2893
what if my array looks like this `Array ( [0] => 1 [1] => 34 ) `
leftout
I guess you could go implode(array_values($array),',').
Ollie2893