There is something wrong with your function.
In your second foreach, you put the variable $namearray inside the loop which on every run resets its value to empty array $namearray = array();. Just put that outside the foreach:
//--> put it here
$namearray = array();
foreach($catidarray as $i) {
$query = "SELECT * FROM Categories WHERE Category_ID = '$i'";
$result = mysqli_query($sql, $query);
while($row = mysqli_fetch_array($result)) {
array_push($namearray, $row['Name']);
}
}
And, I just want to make some suggestions on your function. Since you have the junction table
, you don't really need to have a separate query for product
and category
in order to get your desired values from those tables.
Just do the INNER JOIN to maximize the use of your table relations.
Use your junction table Product_Category
because that's the real purpose why created that.
SELECT *
FROM Product_Category AS a
INNER JOIN Category AS b
ON a.Category_ID = b.Category_ID
WHERE Product_ID = $pid
In your function, you may try this: havent tested but hope this will give you idea.
//INPUT PRODUCT ID, GET ASSOCIATED CATEGORIES
function productcat($pid) {
global $sql;
$query = "SELECT *
FROM Product_Category as a
INNER JOIN Category as b
ON a.Category_ID = b.Category_ID
WHERE Product_ID = {$pid}";
$result = mysqli_query($sql, $query);
$namearray = array();
while($row = mysqli_fetch_array($result)) {
array_push($catidarray, $row['Name']);
}
return $namearray;
}
Then that's it :)
And by the way, in the latest version of php, mysql_ functions are already deprecated. Much better if you will be going to use PDO or MySQLi. Check this also: PDO vs. MySQLi