简体   繁体   中英

Query for display catergories from database php mysql

I'm new to coding with php and using MySQL. I am having trouble to display a list of categories by their ID so that each category is displayed individually as a heading. Instead I got it to display a category name but its only echoing out a category name twice that's the same. Here is my code...

$sql= "SELECT * FROM categories ";
$query = mysql_query($sql); 


while($row = mysql_fetch_array($query))
 {
     $id=$row['id'];
     $cat_name=$row['cat_name'];

 }
 ?>


<ul class="nav nav-list">

 <li class="nav-header"><?php echo $cat_name;?></li>
 <li class="nav-header"><?php echo $cat_name;?></li>
</ul>

You can use this code as-is :

$sql= "SELECT * FROM categories ";
$query = mysql_query($sql); ?>

<ul class="nav nav-list">

<?php while($row = mysql_fetch_array($query)) : ?>
    <li class="nav-header"><?php echo $row['cat_name'];?></li>
<?php endwhile; ?>

</ul>

This will loop through your records and for each record, it will print an entire li with the required data.

Note that separating your PHP code from your HTML code like this has several benefits. It will be better colored in your editor and it is also easier to integrate.

Your li tag is outside the while loop. So the $id and $cat_name is only the last record in the DB, then you echo them twice. That's way you got the same name twice. Try echo the li tag in the loop (but not the ul):

<ul class="nav nav-list">
<?php 
while($row = mysql_fetch_array($query))
 {
     $id=$row['id'];
     $cat_name=$row['cat_name'];

     echo '<li class="nav-header">' .$cat_name. '</li>';
 }
 ?>

</ul>

The reason you are printing the same value out twice is because $cat_name is a string variable and will only hold one value at a time you may want to save the items an array and loop at a seperate time, like such

<?php
$sql= "SELECT * FROM categories ";
$query = mysql_query($sql); 
$category = array();
while($row = mysql_fetch_array($query))
   {
     $array = array(
        id => $row['id'],
        name => $row['cat_name']
     );
     array_push($category,$array);
   }
 ?>
<ul class="nav nav-list">
<?php 
foreach($category as $c)
   {
     echo '<li class="nav-header">'.$c['name'].'</li>';
   }; 
?>
</ul>
    $sql= "SELECT * FROM categories ";
    $query = mysql_query($sql); 


while($row = mysql_fetch_assoc($query))
 {
 ?>

       <ul class="nav nav-list">

                <li class="nav-header"><?php echo $row['id'];  ?></li>
                <li class="nav-header"><?php echo $row['cat_name']; ?></li>
      </ul>
<?php } ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM