Search code examples
phpdatabasedropdown

Use PHP to populate Bootstrap dropdown from database


I know there are a ton of answered questions on this but I must be missing something because nothing is working and I'm losing my mind. Admittedly I don't know what I'm doing but usually can figure it out. Not this time.

I have an html page using bootstrap, and a form on the page that is working fine. Users enter text into the form fields, and PHP takes the form fields, inserts them into a document, and produces a DOC that the user downloads.

I'm trying to put a dropdown menu in the form, and populate the options in the dropdown from a database table on my bluehost server. I've tried hacking my way through 20 different variations, and either the dropdown doesn't populate (example below) or a chunk of code from the query appears surrounding the dropdown on the rendered page.

This is placed above my <!DOCTYPE html> at the top of the page:

<?php


$hostname = "localhost";
$username = "myusername";
$password = "mypassword";
$databaseName = "mydatabase";



$connect = mysqli_connect($hostname, $username, $password, $databaseName);

$query = "SELECT * FROM `mytablename`";

$result1 = mysqli_query($connect, $query);

?>

And here is the code in the form:

<div class="form-group">
  <select class="form-control">

            <?php while($row1 = mysqli_fetch_array($result1)):;?>
            <option><?php echo $row1[1];?></option>

            <?php endwhile;?>

  </select>
</div>

My database table is titled: mytablename

The database has 2 columns - 1) id 2) name

This version doesn't show any errors (unlike some other attempts I've made where parts of the search query render on the page, instead of being executed) and shows a dropdown menu but it's blank without any options.

Can anyone guess where I'm going wrong?


Solution

  • Welp, this is embarrassing, but it looks like the user I was using to connect to the database did not have sufficient permissions. I thought when I created the user I set it up as having all privileges, but apparently not. There goes a whole day of work.

    Thank you to all who looked at this.