PHP MySQL无法从数据库中读取数据

时间:2015-11-28 08:20:53

标签: php html mysql

下拉列表未显示我在数据库中输入的数据

Product Category:
<select name="product_cat">
    <option>Select a Category</option>
    <?php 
    $get_cats = "select * from categories";
    $run_cats = mysqli_query($con, $get_cats);
    while ($row_cats=mysqli_fetch_array($run_cats)){
        $cat_id = $row_cats['cat_id'];
        $cat_title = $row_cats['cat_title'];
        echo "<option>$cat_title</option>";
        }
        ?>
    </select>

4 个答案:

答案 0 :(得分:0)

请尝试以下代码:

<select name="product_cat">
   <option value="">Select a Category</option>
   <?php 
      $get_cats = "select * from categories";
      $run_cats = mysqli_query($con, $get_cats);
      while ($row_cats=mysqli_fetch_array($run_cats)){
        //$cat_id = $row_cats['cat_id'];     // no need to put in another variable
        //$cat_title = $row_cats['cat_title'];    // no need to put in another variable
        echo "<option value='".$row_cats['cat_id']."'>".$row_cats['cat_title']."</option>";
      }
   ?>
</select>

答案 1 :(得分:0)

你只需要改变你的while循环:

while ($row_cats=mysqli_fetch_array($run_cats)){

对此:

while ($row_cats=mysqli_fetch_row($run_cats)){

mysqli_fetch_array()返回数组中表的所有行。您需要将其存储在变量中并进行foreach循环。

mysqli_fetch_row()一次只返回一行。如果已经提取了所有行,它也会返回false,因此您可以在while循环中使用它,就像您一样。

答案 2 :(得分:0)

<label for='product_cat'>Product Category:
    <select name='product_cat'>
        <optgroup label='Select a Category'>
            <option selected='selected' disabled='disabled' hidden='hidden'>Select a Category
            <?php 
                $sql='select * from `categories`';
                $res=mysqli_query( $con, $sql );
                if( $res ){
                    while( $rs=mysqli_fetch_object( $res ) ){
                        echo "<option value='{$rs->cat_id}'>{$rs->cat_title}";
                    }
                }
                mysqli_free_result( $res );
                $con->close();
            ?>
        </optgroup>
    </select>
</label>

答案 3 :(得分:-1)

<html>
    Product Category:
    <?php $get_cats="SELECT * FROM categories"; $run_cats=mysqli_query($con,$get_cats);?>
    <select name="product_cat">
        <option>Select a Category</option>
        <?php while ($row_cats=mysqli_fetch_assoc($run_cats)){?>
            <option value="<?php echo $row_cats['cat_id'];?>"><?php echo $row_cats['cat_title']; ?></option>
        <?php } ?>
    </select>
</html>