My goal is to populate an HTML select box from MySQL using a PHP function. I started by putting the code directly on the HTML page, and I got it working.
<label for="product_Category">Product Category</label>
<?
$field_Name = "category_Name";
$table_Name = "Product_Category";
$sql = "Select " . $field_Name . " From " . $table_Name;
$results = mysqli_query($link, $sql);
echo "<select>";
echo "<option value = \" \" >Select Category"</option>;
while($row = mysqli_fetch_array($results, MYSQLI_ASSOC)){
echo "<option value = ' " .$row[$field_Name] . "'>" . $row[$field_Name]. "</option>";
}
echo "</select>";
?>
I have multiple select boxes, so I thought it would be easier to create a function and pass the table name, and field name as arguments
I moved the PHP function to its own file, and use an include statement in my HTML. But once I tried to call the PHP function, the select box won't populate. The select box shows up on the form like it should, but its empty.
PHP
<?
function Populate_Select($table_Name, $field_Name){
$sql = "Select " . $field_Name . " From " . $table_Name;
$results = mysqli_query($link, $sql);
echo "<select>";
echo "<option value = \" \" >Select Category </option>";
while($row = mysqli_fetch_array($results, MYSQLI_ASSOC)){
echo "<option value = ' " .$row[$field_Name] . "'>" . $row[$field_Name]. " </option>";
}
echo "</select>";
}
?>
DB Config
<?
$host = "localhost";
$db_userName = "root";
$db_Password = "root";
$db_Name = "mydb";
$link = mysqli_connect($host, $db_userName, $db_Password, $db_Name);
if (!$link){
die("Database Connection failed " . mysqli_connect_error);
}
?>
HTML Code
<? include 'PopulateSelect.php' ?>
<? include 'DB_Config.php ?>
<!--Rest of HTML CODE-->
<label for="product_Category">Product Category</label>
<? Populate_Select('Product_Category', 'category_Name'); ?>
Where did I go wrong when I called the function?
Is it better practice to use a function or am I better off just writing separate code for each select box?