Reputation: 65
i have a php file where i am trying to fetch values from database and show in the web page. I have written a foreach loop but it is showing same output for several times. here is my code
<?php
session_start();
$host="localhost";
$user="root";
$pass="";
$db="documentation";
$off=$_GET['id'];
$conn=mysqli_connect($host,$user,$pass,$db);
$query=mysqli_query($conn,"SELECT category_name FROM category WHERE id='$off'");
$rslt=mysqli_fetch_assoc($query);
$query1=mysqli_query($conn,"SELECT cat_description FROM category WHERE id='$off'");
$rslt1=mysqli_fetch_assoc($query1);
$shown=mysqli_query($conn,"SELECT b.subcat_name, b.id, b.description
FROM category a, subcategory b
WHERE b.cat_name = (SELECT category_name FROM category WHERE id='$off')");
?>
<html>
<head>
<title>Category</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="css/mystyle.css">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<?php
foreach ($shown as $showsubn) { ?>
<div class="row">
<div class="col-md-12">
<p class="border1">
<p class="margin">
<i class="fa fa-cube"></i>
<a href="subcat.php?id=<?php echo $showsubn['id']; ?>"><font size="4"><?php implode(" ",$showsubn); echo $showsubn['subcat_name'];?> </font></a>
<p class="margin"><?php implode(" ",$showsubn); echo $showsubn['description'];?></p>
</p>
</p>
<p class="border4"></p>
</div>
</div>
<?php
}; ?>
</div>
</body>
</html>
the output should be canbangla youbangla
but it is showing canbangla canbangla canbangla ...upto 12 several times youbangla youbangla youbangla ...upto 12 several times
Upvotes: 0
Views: 71
Reputation: 2059
Just do this
while ($showsubn = mysqli_fetch_assoc($shown))
Instead of
foreach ($shown as $showsubn)
Hope this will solve your issue
Upvotes: 0
Reputation: 516
Simply do this
<?php
while($showsubn = mysqli_fetch_assoc($shown))
{
?>
<div class="row">
<div class="col-md-12">
<p class="border1">
<p class="margin">
<i class="fa fa-cube"></i>
<a href="subcat.php?id=<?php echo $showsubn['id']; ?>"><font size="4"><?php implode(" ",$showsubn); echo $showsubn['subcat_name'];?> </font></a>
<p class="margin"><?php implode(" ",$showsubn); echo $showsubn['description'];?></p>
</p>
</p>
<p class="border4"></p>
</div>
</div>
<?php }
?>
It will work perfectly.
Upvotes: 0
Reputation: 989
change
foreach ($shown as $showsubn) {
to
while ($showsubn = mysqli_fetch_assoc($shown))
Upvotes: 1
Reputation: 440
Have you tried adding DISTINCT operator to your query?
You can use it like:
$shown=mysqli_query($conn,"SELECT DISTINCT b.subcat_name, b.id, b.description
FROM category a, subcategory b
WHERE b.cat_name = (SELECT category_name FROM category WHERE id='$off')");
Distinct operator displays the unique data depending on which column you chose
Upvotes: 0