简体   繁体   中英

PHP drop down list with pre-selected values

I think I am nearly there with this problem, but I can't quite see why my solution isn't working. I'm trying to pre-select an item from a php drop down list that uses a MySQL table. The drop down list populates as expected, but the pre-select doesn't work. My code:

echo $Trans1E; // Display Existing value
    echo '<p>Trans1: ';
        $q = "SELECT TR1_Name FROM sb_TR1 ORDER BY TR1_Name";
        $r = @mysqli_query ($dbc, $q);
        $row = mysqli_fetch_array ($r, MYSQLI_NUM);
        echo "<select name='Trans1' value=''>Trans1</option>"; // list box select command
        while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC))
        {//Array of records stored in $row
            $selected='';
            if($row[TR1_Name]==$Trans1E) //determine if the row value is the same as the Existing
            {//if it it then mark as selected
                echo "<option value=$row[TR1_Name] selected='selected'>$row[TR1_Name]</option>";
            }
            else
            {// if it is not then just inlcude it in the drop down list
                echo "<option value=$row[TR1_Name] >$row[TR1_Name]</option>";
            }
        }
        echo "</select>";// Closing of list box
    echo '
    </p>';

I've seen similar things on this forum for drop down lists which I've incorporated in my code or at least experimented with but without success, I suspect an error in: if($row[TR1_Name]==$Trans1E), but have run out of thinsg to try.

It seems I was closer to the correct code than I thought, I resolved the problem by adding the line:

$Trans1E=mysqli_real_escape_string($dbc, trim(htmlentities($Trans1E)));

before the code. Despite displaying the content of Trans1E, it seems there was an unwanted element in it, which I hadn't spotted so I thought the code further down was at fault. Thanks for you comments. Hope this helps others.

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