简体   繁体   中英

Adding a variable value as an option in a PHP echo created drop down menu

I am using a PHP script within an HTML page to create a dropdown menu with results populated from a database. I am using the PHP script in the HTML page because I'd like the dropdown menu to remain on the same page as a number of options.

When creating an option in the dropdown menu via an echo, it won't allow me to use the value of a variable (ie the value of a field in the database that has been retrieved) in the option tag. Here is the code:

<select name="comics">
    <OPTION>Select an option</OPTION>; 
    <?php
        include_once('includes/conn.inc.php');
        $query = ("SELECT comicID, comicName  FROM comic");
        $result = mysqli_query($conn, $query);
        while ($row = $result->fetch_assoc()) 
        {
        echo "<option> .$row['comicName']. </option>";
        }
    ?>
</select>

As is, the code creates the drop down menu and adds the "Select an option" line. The second option is created, but the value reads as " .$row['comicName']. " instead of, for example, "Superman".

Thanks in advance.

Your solution tries performing concatenation without closing the double-quotes first, so it treats the variable as a string. Try this:

echo "<option>" . $row['comicName'] . "</option>";

Try:

<select name="comics">
    <OPTION>Select an option</OPTION>; 
    <?php
        include_once('includes/conn.inc.php');
        $query = ("SELECT comicID, comicName  FROM comic");
        $result = mysqli_query($conn, $query);
        while ($row = $result->fetch_assoc()) 
        {
        echo "<option value='".$row['comicName']."'>".$row['comicName']."</option>";
        }
    ?>
</select>

Let me know if works.

Have you named the file with a php extension ? try doing a print_r with $result before the while loop

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