Dropdown List from MySQL Column using mysqli [clos

2019-03-07 03:19发布

问题:

I have a MySQL table named Users with columns Name and NameID.

Like...
Name | NameID
Brad | bd
Tom | ts

I'm trying to pull the all the Name values and have them populate a dropdown list using mysqli. I'm running into problems and hoping someone here can help.

I'm new to mysqli, so struggling a bit here. Here's the code..

connect.php...

<?php

$dbname = 'mydabase';
$dbuser = 'myuser';
$dbpass = 'mypass';

?>

In index.php...

<?php
include ("connect.php");

$db = new mysqli('localhost', $dbuser, $dbpass, $dbnam);
if (!$db) {
  exit('Connect Error (' . mysqli_connect_errno() . ') '
       . mysqli_connect_error());
} 
?>

    <div class="label">Select Name:</div>

    <select name="names">
    <option value = "">---Select---</option>
    <?php
    $queryusers = "SELECT `Name` FROM `Users` ";
    $db = mysqli_query($queryusers);
    while ( $d=mysqli_fetch_assoc($db)) {
      echo "<option value='{".$d['Name']."}'></option>";
    }
    ?>
      </select>  

回答1:

The reason your select doesn't get populated is because the mysqli_query doesn't get a connection supplied.

Change:

$db = mysqli_query($queryusers);

Into:

$db = mysqli_query($db, $queryusers);

Also add the name between (else you get a list with no text):

while ( $d=mysqli_fetch_assoc($db)) {
  echo "<option value='{".$d['Name']."}'>".$d['Name']."</option>";
}

Hope this helped you out!



回答2:

If you inicialized an object, then you should continue using mysqli as object.

There is no need to use prepared statements, but it isn't wrong.

<?php
include ("connect.php");

$db = new mysqli('localhost', $dbuser, $dbpass, $dbnam);
?>
<div class="label">Select Name:</div>
<select name="names">
<option value = "">---Select---</option>
<?php
$stmt = $db->prepare("SELECT `Name` FROM `Users`");
$stmt->execute();
$stmt->bind_result($name);
while ($stmt->fetch()){
    echo "<option value='$name'></option>";
}
$stmt->close();
?>
</select> 


标签: php mysql mysqli