Populate options using PHP

I am trying to populate my select boxes options with the results from a query, but its not working…


    <select name="p_name" class="form-control" id="p_name">
<?php

$sql = "SELECT `name` FROM `providers` WHERE `display` == 1";  

$stmt = $dbh->prepare($sql);

$stmt->execute();

$names = Array();

while ($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {      
$names[] =  $row[i];  
     
echo "<option value=".$names[i].">".$names[i]."</option>";     

$i= $i+1;

}
?>    
</select>

What am I missing?

You are using a mix of OO database access (PDO?) and a mysql_ fetch command (which should give an error because you’re passing it a string instead of a result set).

also in SQL query use only single “=” instead of “==”

$sql = "SELECT `name` FROM `providers` WHERE `display` = 1";

ok, will make the change to the query.

I thought the PDO is the safest method for this… Should I just stick with the non-PDO way?

I used the PDO way, the OO way gave me a warning,


<?php
$sql = "SELECT `name` FROM `providers` WHERE `display` = 1 ORDER By `name`";


foreach ($dbh->query($sql) as $row){
//Array or records stored in $row
echo "<option value=".$row[id].">$row[name]</option>"; 
/* Option values are added by looping through the array */ 
}
?>

You can query within content like so.

<select name="p_name" class="form-control" id="p_name">
<?php
$sql = "SELECT `name` FROM `providers` WHERE `display` = 1";
$stmt = $dbh->prepare($sql);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
	echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
?>
</select>

Or build your $names array and loop through it anywhere on the page with foreach

<?php
$sql = "SELECT `name` FROM `providers` WHERE `display` = 1";
$stmt = $dbh->prepare($sql);
$stmt->execute();

$names = Array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
	$names[] = $row['name'];
}
?>

<select name="p_name" class="form-control" id="p_name">
<?php
foreach($names as $name):
	echo '<option value="'.$name.'">'.$name.'</option>';
endforeach;
?>
</select>

You can try out my PHP GUI API, it provides ways to easily populate dropdown menu with options, either pulling from your database or hard-coded:
http://www.phpclasses.org/package/7857-PHP-Render-HTML-pages-composed-programmatically.html