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()开发者_Python百科;
$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'];
}
}
do it like this:
$dbc = mysqli_query($mysqli,"SELECT category
FROM categories
WHERE id IN (" .implode(",", $array). ")");
$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.
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.
精彩评论