0

I am trying to connect to MySQL and populate the data to Dropdown. Here is my code. Some reason dropdown is not getting populated. Please suggest.

Here is the code.

<html>
<body>

<?php
$mysqli_connection = new mysqli($db_host, $db_username, $db_password, $db_database);
if (isset($_POST['Submit_1'])) {
    require 'submit.php';
    require 'validate.php';
    if ($form_errors = validate_form()) {
        show_form($form_errors);
    }
    else
    {
        form_submit_1();
    }
}
else
{
    show_form();
}
function show_form($errors = '')
{
    // were there any errors?  
    if ($errors) {
        //show errors
    }

    ?>
<form name="myForm" id="myForm" method="post">
    <?php
    $sql = "SELECT id, code FROM table1";
    $result11 = $mysqli_connection->query($sql);
    echo " <select name = \"state1\" id=\"state1\">";
    while ($row = $result11->fetch_assoc()) {
        echo "<option value = $row[id]>$row[code]</option>";
    }
    echo "</select>";
    ?>
</form>
    </body>
</html>
<?php
} // End of show_form()
?>

2 Answers 2

4

This part:

echo "<option value = $row[id]>$row[code]</option>";

Is not valid, it should be something like this:

echo "<option value=\"{$row['id']}\">{$row['code']}</option>";
Sign up to request clarification or add additional context in comments.

1 Comment

It still doesn't work. If I move the dropdown code logic above the function show_form($errors = ''), it works.
0

You'll have to escape from the string back to the PHP layer.

echo "<option value=\"".$row['id']."\">".$row['code']."</option>";

That way you'll concatanate the PHP value of the variables with the string elements you're creating.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.