Select option menu read from database and use it's values

前端 未结 3 1376
野趣味
野趣味 2021-01-16 15:56


        
相关标签:
3条回答
  • 2021-01-16 16:33

    I would recommend making sure that you order the fields in the SQL Query to match the order you want them in and then use:

    $query = "SELECT path, name, id FROM categories ORDER BY ID DESC LIMIT  0,6";
    
    echo "<option value='".$row[0]."'>'".$row[1]."'</option>";
    

    Your code will then be much more reusable as a 'code snippet', all you need to do is write a new SQL Query

    0 讨论(0)
  • 2021-01-16 16:45

    EDIT:(reduces ur code)

    <?php
    mysql_connect("localhost", "root","") or die(mysql_error());
    mysql_select_db("tnews2") or die(mysql_error());
    
    $query = "SELECT name,id,path FROM categories ORDER BY ID DESC LIMIT  0,6";
    $result = mysql_query($query) or die(mysql_error()."[".$query."]");
    ?>
    
    <select name="categories">
    <?php 
    while ($row = mysql_fetch_array($result))
    {
        echo "<option value='".$row['path']."'>'".$row['name']."'</option>";
    }
    ?>        
    </select>
    
    0 讨论(0)
  • 2021-01-16 16:47

    I would prefer doing it like this using mysqli

    <?php
    /* Database connection settings */
    $host = 'localhost';
    $user = 'root';
    $pass = '';
    $db = 'tnews2';
    $mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
    
    /* Your query */
    $result = $mysqli->query("SELECT name,id,path FROM categories ORDER BY ID DESC LIMIT  0,6";) or die($mysqli->error);
    ?>
    

    Then add the elements to html like this:

    <select name="categories">
        <option value="Select School">Select Shool</option>
        <?php
        while ($row = mysqli_fetch_array($result)) {
            echo "<option value='" . $row['path'] . "'>'" . $row['name'] . "'</option>";
        }
        ?>        
    </select>
    
    0 讨论(0)
提交回复
热议问题