在php

时间:2016-01-04 07:46:20

标签: php mysql

我有一个php文件,我试图从数据库中获取值并显示在网页中。我编写了一个foreach循环,但是它多次显示相同的输出。这是我的代码

<?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>

输出应该是 canbangla youbangla

但它正在显示 canbangla canbangla canbangla ...多达12次 youbangla youbangla youbangla ...多达12次

4 个答案:

答案 0 :(得分:1)

变化

foreach ($shown as $showsubn) {

while ($showsubn = mysqli_fetch_assoc($shown))

答案 1 :(得分:0)

您是否尝试在查询中添加DISTINCT运算符?

您可以像以下一样使用它:

$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运算符根据您选择的列显示唯一数据

答案 2 :(得分:0)

就这样做

while ($showsubn = mysqli_fetch_assoc($shown))

而不是

foreach ($shown as $showsubn)

希望这能解决您的问题

答案 3 :(得分:0)

只需这样做

<?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 } 
?>

它会完美运作。