Not displaying data from mysql
Question by Ken
I have this table,
--------------------------------------------
| products_id | related_products_ids |
| -----------------------------------------
| 1 | 1,2,3,4,6, |
| -----------------------------------------
| 2 | 1,2,3, |
| -----------------------------------------
| 3 | 1,2, |
-------------------------------------------
I want to display those related products in the product page. How can I do that?
Example, I’m in the product page where products_id
is 1, i want to display the products from a table like table_name1
by related_products_ids
.
I have used this code for displaying data,
$sql = "SELECT related_products_ids FROM ".TABLE_RELATED_PRODUCTS." where products_id = '" . (int)$_GET["products_id"]."'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$lst_rp = explode(',', $row['related_products_ids']);
echo '<ul>';
foreach($lst_rp as $rp_id) {
$res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='" . $rp_id . "'";
$result1 = mysql_query($res);
$row1 = mysql_fetch_array($result1);
echo '<li>'.$row1['products_name'].'</li>';
}
echo '</ul>';
However, it displays nothing.. Is there something wrong with my code? Do you have any solution for this?
Thank you.
Answer by Starx
You have placed the actual database query section outside of the loop.
You should include this within the foreach
loop, so that every time, a new query runs and you will receive the results as you anticipated.
foreach($lst_rp as $rp_id) {
$res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='" . $rp_id . "'";
$result1 = mysql_query($res);
while($row1 = mysql_fetch_array($result1)) {
echo $row1['products_name'];
}
}
And one more thing, since you are using double quotes to wrap your query, you can shorten it two
$res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='$rp_id'";
Update
Use the following code to ensure the <li>
is not empty
foreach($lst_rp as $rp_id) {
$res = "SELECT products_id, products_name FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id='" . $rp_id . "'";
$result1 = mysql_query($res);
$row1 = mysql_fetch_array($result1);
echo !empty($row1['products_name']) ? '<li>'.$row1['products_name'].'</li>' : '';
}