AyeitzaMoleRat
AyeitzaMoleRat

Reputation: 49

Using MYSQLI to populate dropdown box - PHP

Hey guys I am having some issues populating a drop down box using MYSQLI. The code I have so far is:

<?php
session_start();
if (!isset($_SESSION['myusername'])){
    header("location:index.php");
}
include_once './includes/checkperm.php';
$permlevel = check_perm($_SESSION['myusername']);
if ($permlevel < "90" ) {
    header("location:permtolow.php");
    exit;
}
require_once($_SERVER['DOCUMENT_ROOT'].'/../dbcon.php');
?>

<div class="label">Select Name:</div>
<select name="names">
<option value = "">---Select---</option>

<?php
$queryusers = "SELECT username FROM finance";
$query = mysqli_query($con, $queryusers);
while ( $d=mysqli_fetch_array($query)) {
echo "<option value='{".$d['username']."}'>".$d['username']."</option>";
}
echo '</select>'
?>

Unfortunately the drop down box stays empty. I am probably missing something simple.

Upvotes: 0

Views: 1953

Answers (2)

AyeitzaMoleRat
AyeitzaMoleRat

Reputation: 49

The issue was when I called the require to the database connection: Here is the fixed script, moving the "require" to the second PHP block.

<?php
session_start();
if (!isset($_SESSION['myusername'])){
    header("location:index.php");
    exit;
}
include_once './includes/checkperm.php';
$permlevel = check_perm($_SESSION['myusername']);
if ($permlevel < "90" ) {
    header("location:permtolow.php");
    exit;
}
?>


<?php
require($_SERVER['DOCUMENT_ROOT'].'/../dbcon.php');
$queryusers = "SELECT * FROM finance";
$query = mysqli_query($con, $queryusers) or die (mysqli_error());
echo '<div class="label">Select Name:</div>';
echo '<select username="username">';
echo '<option value = "">---Select---</option>';
while ( $d=mysqli_fetch_array($query)) {
echo "<option value='{".$d['username']."}'>".$d['username']."</option>";
}
echo '</select>';
?>

Upvotes: 0

Dmitry Zayats
Dmitry Zayats

Reputation: 473

The problem with your code is following.
If you simplify it to a bare minimum

  1 #!/usr/bin/php
  2 <?php
  3 $ar=array('one','two','three');
  4 foreach ($ar as $val){
  5 echo "<option value='{".$val."}'></option>";
  6 printf("\n");
  7 }
  8 ?>

And run it - you will end up with

[root@sshbuild ~]# ./phptest.php
<option value='{one}'></option>
<option value='{two}'></option>
<option value='{three}'></option>

See the problem?
You are missing values in between tags
Output should be like this

[root@sshbuild ~]# ./phptest.php
<option value='{one}'>one</option>
<option value='{two}'>two</option>
<option value='{three}'>three</option>

So what you need to do is this

echo "<option value='{".$d['username']."}'>".$d['username']."</option>";

Upvotes: 0

Related Questions