I have searched the internet and I just cant seem to get my head around what to do in order to populate my drop down list from my database.
I have a table called users where there are roles such as chairman, secretary and admin.
My code is as follows:
<td>
<span id="spryselect1">
<select name="chairperson" id="chairperson">
</select>
<span class="selectRequiredMsg">You Must Choose A Chairperson For This Meeting</span>
</span>
</td>
How do I populate a drop down list so that it shows all the chairman available?
Something like this should do the trick. You probably need to work on the wrapper function that creates the drop-down but it's a start. If you are not comfortable with mysql_fetch_object() and you are more familiar with arrays then you can user mysql_fetch_array()
<?php
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");
function sql_to_select ($result) {
$output = '<select name="chairperson" id="chairperson">'
while ($row = mysql_fetch_object($result)) {
$output. = '<option value="' . $row->role_id . '">' . $row->role . '</option>';
$output .= '</select>';
return $output
}
?>
<html>
<body>
<h3>Here will come the select</h3>
<div class="wrap-select">
<?php print sql_to_select($result); ?>
</div>
</body>
</html>
At a very basic level, you need to loop through each result and output an '...' element to the list:
<select name="chairperson" id="chairperson">
<?php
// ... Assumes you already connected to and selected a database
$result = mysql_query('SELECT ...');
foreach (mysql_fetch_assoc($result) as $row) :
?>
<option value="<?= $row->id_column; ?>"><?= $row->column_to_display; ?></option>
<?php
endforeach;
?>
</select>
Obviously, you'll need to replace "id_column" with your primary key or whatever you want to use to uniquely identify the list item, and "column_to_display" should be "name" or "title" or whatever should be displayed in the option.
Related
I'm new in PHP.
I have a database with 5 columns. "id" "fldName" "fldPrice" "fldSupplier" and "fldPackage".
I have a HTML table with select options where I output "fldName" where "fldPackage" has a spesific value. I have made this work, but I would also like to output the corresponding "fldPrice" from the selected "fldName" when it's chosen. I'm stuck on how to do this.
This is my php:
<?php
function conTroller(){
include("includes/dbh.php");?>
<?php $sql = "SELECT * FROM tbl_price WHERE fldPackage='controller'";
$result = mysqli_query($conn, $sql);
if($result->num_rows> 0){
$options= mysqli_fetch_all($result, MYSQLI_ASSOC);}
foreach ($options as $option) { ?>
<option><?php echo $option['fldName']; ?> </option><?php }}
?>
and this is my HTML
<td><b>Electrical package</b></td>
<td>
<select id="1" class="custom-select" required onchange="ePkg(event)">
<option selected value="">None</option>
<?php conTroller(); ?>
</select>
</td>
<td>I want "fldPrice" to update here when I choose from the options</td>
<td>istL</td>
<td>Select controller</td>
Can anyone help?
I have been reading, googling and looking for similar problems. The biggest problem for me is that I'm not really sure what to search for.
For the simplicity for only updating price when selectbox changed, I suggest to use DOM Manipulation using Javascript
<?php
function conTroller() {
include("includes/dbh.php");
$sql = "SELECT * FROM tbl_price WHERE fldPackage='controller'";
$result = mysqli_query($conn, $sql);
if($result->num_rows> 0){
$options= mysqli_fetch_all($result, MYSQLI_ASSOC);}
foreach ($options as $option) { ?>
<!-- add attribute "data-price" so javascript can get price value from the selected option -->
<option data-price="<?php echo $option['fldPrice']; ?>"><?php echo $option['fldName']; ?> </option><?php
}
}?>
<td><b>Electrical package</b></td>
<td>
<!-- add a function in onchange to update price whenever selectbox changed -->
<select id="1" class="custom-select" required onchange="ePkg(event); updatePrice(this)">
<option selected value="">None</option>
<?php conTroller(); ?>
</select>
</td>
<!-- add attibute "id" so we can access the element to be updated -->
<td id="price-field">I want "fldPrice" to update here when I choose from the options</td>
<td>istL</td>
<td>Select controller</td>
<script>
// function to update price from selected option
function updatePrice(selectbox) {
var price = selectbox.selectedOptions[0].attributes['data-price'].value || '- no price set -';
document.getElementById('price-field').innerHTML = price;
}
</script>
For more advanced flow (eg: getting more product info other than price like description, etc), you will need a separate php file for displaying product info and fetch it using AJAX call. See some tutorial about AJAX and PHP
Steps I did:
PDO is safer.
The first function returns data.
The other is making a presentation.
An additional div with id='fldPrice' will be the place to display the price.
A significant part of the code was done by javascript
function getPackage() {
$db = conn();
$sql = "SELECT id, fldName, fldPrice, fldSupplier, fldPackage FROM tbl_price WHERE fldPackage='controller'";
$sth = $db->prepare($sql);
$sth->execute();
return $sth->fetchAll(PDO::FETCH_ASSOC);
}
function conTroller() {
$options = getPackage();
foreach ($options as $option) {
echo "<option>" . $option['fldName'] . "</option>";
}
}
function ePkg(ev) {
let prices = JSON.parse('<?php echo json_encode(getPackage()); ?>');
let select = document.getElementById('1');
let fldName = select.options[select.selectedIndex].value;
for (let i = 0; i < prices.length; i++) {
if (prices[i]['fldName'] === fldName) {
let d = document.getElementById('fldPrice');
d.innerHTML = 'Prices: ' + prices[i]['fldPrice'];
}
}
}
<td><b>Electrical package</b></td>
<td>
<select id="1" class="custom-select" required onchange="ePkg(event)">
<option selected value="">None</option>
<?php conTroller(); ?>
</select>
</td>
<td>I want "fldPrice" to update here when I choose from the options</td>
<td>List</td>
<td>Select controller</td>
<div id="fldPrice"></div>
I am new to PHP and trying to make dynamic list box using SQL
<label> Select Sport</label>
<select name = "Sport">
<option value = "">Select Sport</option>
<?php
$all = "SELECT * FROM EventTable";
$result = $pdo->query($all);
foreach($result as $Sport){
?>
<option value ="<?php echo $Sport['Sport']; ?>"></option>
<?php
}
?>
</select>
But its printing BLANK space
Try this:
<select name="">
foreach($result as $Sport){
?>
<option value ="<?php echo $Sport['Sport']; ?>"><?php echo $Sport['Sport']; ?></option> // The value between <option> value </option> is the value which is to be shown in the dropdown, without this it is showing blank
<?php
}
</select>
You probably shouldn't use SELECT *, but since you're learning, I digress. Also, I personally have a hard time reading a lot of opening and closing php tags scattered throughout plus they often give weird results than what you're expecting, so this is how I'd write it.
<?php
$all = "SELECT * FROM EventTable";
$result = $pdo->query($all);
foreach($result as $sport)
{
echo "<option value =" . $sport['Sport'] . ">" . $sport['Sport'] . "</option>";
}
?>
The blank spaces indicates that you are actually hitting the loop and iterating, but the values for that array item are null. Are you sure the field name isn't 'sport' instead of 'Sport'?
I am trying to use php code within html to grab content from a database to populate the values for a drop down menu (see below). When I run the php script on its own (test.php) I get all the expected values. When nested within html I get nothing but a single blank value under Select a Species. I would expect this to run through the while loop more than once as there are about 7 values returned and I would also expect the contents to include data derived from the table.
What I am attempting is possible correct??
Is it just an error with code (no errors popping up in the logs)
<label for="select">Species Observed : </label>
<select name="select" class="textfields" id="species">
<option id = "0">-- Select a Species -- </option>
<?php
$con = mysqli_connect("localhost","xxx","xxxx","databases");
$result = mysqli_query($con, "SELECT * FROM bc_species WHERE 1");
while ($row = $result->fetch_assoc()){
?>
<option><?php echo $row['species'];?></option>
<?php } ?>
</select>
<option><?php echo $row["species"]; ?></option>
<?php
$optionData = '<option id = "0">-- Select a Species -- </option>';
$con = mysqli_connect("localhost","xxx","xxxx","databases");
$result = mysqli_query($con, "SELECT * FROM bc_species WHERE 1");
while ($row = $result->fetch_assoc()){
$optionData .= "<option>".$row['species']."</option>" ;
}
?>
<label for="select">Species Observed : </label>
<select name="select" class="textfields" id="species">
<?php echo $optionData;?>
</select>
//Put your fetched data on an array then loop them like this
<?php
foreach ($list as $data => $item) {
?>
<option value="<?php echo $data?>">
<?php echo $data?>
</option>
<?php
}
?>
This should work:
<label for="select">Species Observed : </label>
<select name="select" class="textfields" id="species">
<option id = "0">-- Select a Species -- </option>
<?php
$con = mysqli_connect("localhost","xxx","xxxx","databases");
$result = mysqli_query($con, "SELECT * FROM bc_species");
while ($row = $result->fetch_assoc()){
echo '<option>'. $row["species"].'</option>
} ?>
</select>
You were not iterating through the values within the HTML <option> tags, so I moved those into the while loop. (notice the PHP section includes echoing those tags).
I also removed the unnecessary "SQL injection-looking" where 1 clause from your query.
The problem I have is that there is no results in the "category" option. I tried to use two whiles but that doesn't work either.
This is my php:
try{
$sel=$pdo->prepare("Select * from
actors inner join cat
on actors.id=cat.id");
$sel->bindColumn(1,$actors_id);
$sel->bindColumn(2,$actors);
$sel->bindColumn(3,$cat_id);
$sel->bindColumn(4,$cat);
$sel->execute();
}catch(PDOException $e){
die("error: " . $e->getMessage());
}
And This is my html:
<form action="" method="post">
<label for="author">Author</label>
<Select id="author">
//Show data from php file:
<?php while($sel->fetch()):?>
<?php echo "<option value='$actors_id'>$actors</option>";?>
<?php endwhile; ?>
</Select>
<label for="category">Category</label>
<Select id="category">
//Show data again from php file:
<?php while($sel->fetch()):?>
<?php echo "<option value='$cat_id'>$cat</option>";?>
<?php endwhile; ?>
</Select>
</form>
And this is how it looks like:
As you can see, there is no info display in the "category" option.
If I change the html to something like this, it doesn't work either:
<Select id="author">
<?php while($sel->fetch()):?>
<?php echo "<option value='$actors_id'>$actors</option>";?>
</Select>
<label for="category">Category</label>
<Select id="category">
<?php echo "<option value='$cat_id'>$cat</option>";?>
<?php endwhile; ?>
</Select>
Now it looks like this:
Do you have any suggestion?
Your first while loop fetches all rows from the PDOStatement object, so when you call while ($sel->fetch()) a second time, it immediately returns false. If you want to use the results in essentially two separate loops, fetch all rows first into an array of rows, then loop over that array. Do so with fetchAll() instead of binding to variables via bindColumn().
In fact, I would almost always recommend fetching first rather than during the display logic, except for very large rowsets where the memory consumed by fetching it all at once would be taxing on your system.
// Get all the rows as an array
$rows = $sel->fetchAll(PDO::FETCH_ASOC);
// Later loop for the items you need as many times as you need
// Each new foreach will iterate the entire $rows array from start to end
<?php foreach ($rows as $row): ?>
<?php echo "<option value='{$row['actors_id']}'>" . htmlspecialchars($row['actors']) . "</option>";?>
<?php endforeach; ?>
<?php foreach ($rows as $row): ?>
<?php echo "<option value='{$row['cat_id']}'>" . htmlspecialchars($row['cat']) . "</option>";?>
<?php endforeach; ?>
Don't forget to call htmlspecialchars() on the output, to ensure it is properly encoded for HTML. I haven't done so on cat_id,actors_id on the assumption those are known to be integers, but if not, then you should use htmlspecialchars($row['cat_id'], ENT_QUOTES) to ensure the HTML attributes are correctly quoted.
You need to be cleaner in your return -
<?php
$result = $sel->fetchAll(PDO::FETCH_OBJ); //return an object
foreach($result as $actor) {
echo '<option value=' . $actors->actor_id .'>'. $actor->actors .'</option>'; // note the quotes
}
?>
You can loop through the result as many times as you need to, without re-fetching the data.
I'm back and this one might be a little tricky but we will find out! :D
Okay I am using php to self populate my select fields so I don't have to continuously update the options when new agents join. I am using ajax (javascript) for this part of the page and I have had no problems with this except with the company select field.
Live site
All my select fields work with out any problems but the Company field which will display nothing only on companies that seem to have "&" in the name. (Two companies still work with "&" in the name)
List of non-functioning Companies:
-Anthem
-Bogart
-Burnham
-Church Insurance
-Fawcett
-JRM
-Kenneth B. Brown
-Newton
-Sam F.
-Sherrill
-Wallace & Turner
PHP Company select code: (The if/else statement in the companies field would ideally be if ($row['Company'] !== NULL) {
echo '<option value="'.$row['Company'].'">'.$row['Company'].'</option>';
} but for some reason it will echo in a blank space in the option dropdown.)
<label for="company">Company</label><br />
<select id="company" name="users" onChange="showUser(this.value)">
<?php include 'login.php';
$result = mysqli_query($con, "SELECT DISTINCT Company FROM `roster` ORDER BY Company ASC;");
echo '<option value="">' . 'Select a Company' .'</option>';
while ($row = mysqli_fetch_array($result)) {
if ($row['Company'] == NULL) {
}
else {
echo '<option value="'.$row['Company'].'">'.$row['Company'].'</option>';
}
}
?>
</select>
PHP for other select fields:
<label for="last">Last Name</label><br />
<select id="last" name="Last_Name" onChange="showUser(this.value)">
<?php include 'login.php';
$result = mysqli_query($con, "SELECT DISTINCT Last_Name FROM `roster` ORDER BY Last_Name ASC;");
echo '<option value="">' . 'Select an Agent' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['Last_Name'].'">'.$row['Last_Name'].'</option>';
}
?>
</select>
Any Ideas on this one? If you need to see the process.php page which echos in the results then just ask! Thanks a million to anyone who helps out.
How the HTML looks when populated through php:
<select id="company" name="users" onchange="showUser(this.value)">
<option value="">Select a Company</option><option value="A.R.T. Group">A.R.T. Group</option><option value="ALPHA Benefits">ALPHA Benefits</option>
</select>
I only included a few since 80ish of them is one massive line of html.
You need to urlencode the parameter that is being passed via ajax. The ampersand is telling PHP that $_GET['q'] is complete and a new $_GET variable is starting.
Notice the %26 for the ampersand returns the desired result.
http://healthbenefitsohio.com/process.php?q=Anthem%20Blue%20Cross%20%26%20Blue%20Shield
Your company options should look like this:
echo '<option value="'.urlencode($row['Company']).'">'.$row['Company'].'</option>';
For good measure, I would also encode the display
echo '<option value="'.urlencode($row['Company']).'">'.htmlspecialchars($row['Company'],ENT_QUOTES).'</option>';