Select values based on database result - php

I have a form with a multi select which presents the user with a list of groups to chose from,which is then saved in the database. My aim is that when the user wants to edit his information, the groups saved in the database to be selected and the others not to be selected. Please, see my code and advise.
I populate the saved groups to a variable
$groups = array($row['groups']); // This outputs the groupId from the db eg 1,2,3,6
Populate groups to a multi select
<div class="form-group">
<!-- <label>Church Groups: </label> -->
<select name="groups[]" class="form-control mandatory" id="groups" multiple="multiple" >
<?php
$sql="SELECT ID,UCASE(groupName) AS groupName FROM tblgroups WHERE (congregationId=?)";
$stmt=mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt,$sql);
mysqli_stmt_bind_param($stmt,'i',$congId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result)) {
$selected = "";
if(in_array($row['ID'],$groups)){
$selected = "selected";
}
echo '<option value='.$row['ID'].' '.$selected.'>'.$row['groupName'].'</option>';
}
?>
</select>
Thats my code but it doesn't work. If the first group in the list was saved, only that group is selected all others remain unselected whether in the db or not.

<div class="form-group">
<!-- <label>Church Groups: </label> -->
<select name="groups[]" class="form-control mandatory" id="groups" multiple="multiple" >
<?php
$sql="SELECT ID,UCASE(groupName) AS groupName FROM tblgroups WHERE (congregationId=?)";
$stmt=mysqli_stmt_init($con);
mysqli_stmt_prepare($stmt,$sql);
mysqli_stmt_bind_param($stmt,'i',$congId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result)) {
$selected = "";
if(in_array($row['ID'],$groups)){
$selected = "selected";
}
echo '<option value='.$row['ID'].' '.$selected.'>'.$row['groupName'].'</option>';
}
?>
</select>
Using your code, I have uncommented the line you commented out and introduced a variable that will be blank if the value is not in the group, otherwise it will have the value "selected", which achieves the same functionality as selected = "selelected"

First of all, assuming that your $result element is correct, you need something like this.
<?php
while ($row = mysqli_fetch_array($result)) {
$isSel = in_array($row['ID'],$groups)? "selected" : "";
echo "<option value=\"".$row['ID']."\" $isSel >".$row['groupName']."</option>";
}
?>
It is just a matter of order and linearity:
Populate a $isSel variable that contains the selected string only when your conditions are met
Print all the options, and always append $isSel. It will just contain selected only when it is required
But there are other two issues preventing your drop-down menu to be shown as expected:
Remove the square brackets [] from the select name. They are preventing the correct parsering of the multiple attribute
You don't need to specify multiple="multiple". Just multiple is enough (see here). You did also the same mistake with selected="selected": just selected is enough
So, your <select> tag definition becomes
<select name="groupsABC" class="form-control mandatory" id="groups" multiple >
instead of
<select name="groups[]" class="form-control mandatory" id="groups" multiple="multiple" >

Related

Selected Dropdown data will not display in another page

I have a dropdown bar that is displayed using php.
<select id = "equipment" name="dropdwn" class="form-control">
<option selected="" disabled="">Select Equipment</option>
<?php
$sql = mysqli_query($conn, "SELECT resource_name From resources WHERE resource_type = 'EQUIPMENT';");
$row = mysqli_num_rows($sql);
while ($row = mysqli_fetch_array($sql)){
echo "<option name = 'equipment' value ='". $row['resource_name'] ."'>" .$row['resource_name'] ."</option>" ;
}
?>
</select>
So I want to display the data that is being selected from that dropdown to another page.
I tried this and it does not work. It gives me an error "Notice: Undefined index: equipment"
<?php
include('dbconnector.php');
$equipment = $_POST['equipment'];
echo $equipment;
?>
If you could help me I would really appreciate it. Thanks ahead!
Change select name to equipment:
See below:
<select id = "equipment" name="equipment" class="form-control">
<option selected="" disabled="">Select Equipment</option>
<?php
$sql = mysqli_query($conn, "SELECT resource_name From resources WHERE resource_type = 'EQUIPMENT';");
$row = mysqli_num_rows($sql);
while ($row = mysqli_fetch_array($sql)){
echo "<option name = 'equipment' value ='". $row['resource_name'] ."'>" .$row['resource_name'] ."</option>" ;
}
?>
</select>
There are many selectors for HTML form elements
1) id -> used for css and javascript purposes (unique for each element).
2) class -> used for css and javascript purposes (multiple elements can have same class).
3) name -> This selector is very important. When we get our HTML form submitted to PHP, the elements are accessed with this selector.
For example:
<form method="post"...>
<input name="student" type="text" id="id_student"/>
...
If we submit the above form, in PHP we will the texbox value through:
$_POST['student']
So, please correct your name attribute of drop down to make the page working.

Displaying default value through select tag

I am having trouble passing & displaying default value for select tag. So, I have tried different variants of select and option tag but I am not able to get this right.
I want to fetch different options in form of a drop down menu. I want to display a default value in it. ($categorytemp[$i] in code). On displaying the form
A user can update this choice; or
A user can select the same choice again; or
A user can not change it at all.
Expected result for the above activity should be update, update, default value for $category
Below is the snapshot of my code
<select name="category" value="<?php echo $categorytemp[$i] ?>">
<?php
$sql = "SELECT * FROM education_details";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result))
{
$education_category = $row["id"];
$education_name= $row["name"];
?>
<option value='<?php echo $education_category?>'><?php echo $education_name;?></option>
<?php
}
?>
</select>
I tried using the option tag with selected attribute but that is making things more complicated. For example, if I use
<select name="category" value="<?php echo $categorytemp[$i] ?>">
<option selected="selected"><?php echo $categorytemp[$i]; ?> </option>
<?php
$sql = "SELECT * FROM education_details";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result))
{
$education_category = $row["id"];
$education_name= $row["name"];
?>
<option value='<?php echo $education_category?>'><?php echo $education_name;?></option>
<?php
}
?>
</select>
It displays the form as desired but on making no selection, it passes null value in the category. I have gone through questions of similar type asked earlier, but they do not answer my query to my satisfaction
You do it with a "selected" attribute of a given <option> and not in the <select> tag with the value attribute.
Check these two:
http://www.w3schools.com/tags/tag_select.asp
http://www.w3schools.com/tags/tag_option.asp
Have you consider using Javascript on the form submit to achieve it?
Another option would be a hidden field with default value before the select and an hidden option of the select field:
<html>
<head>
<body>
<form method="POST" action="">
<input type="hidden" name="dropdown" value="default" />
<select name="dropdown">
<option selected disabled hidden style="display: none" value="default"></option>
<option>1</option>
<option>2</option>
<input type="submit" value="send" />
</form>
</body>
</html>
Is $categoryTemp[$i] an ID or a name? If it is the ID and you are wanting to check the result against it to determine the default option to display then something along these lines would select the option that is equal to the value of $categoryTemp[$i].
<option <?php echo ($categorytemp[$i] == $education_category ? 'selected' : ''); ?>
So if $categorytemp[$i] = 1 and $education_category = 1 then that option would be marked selected and be displayed when the page loaded
This did the trick. When no value is selected, pass the default value as value in option
<select name="category" >
<option value='<?php echo $categorytemp[$i]?>'><?php echo $categorytemp[$i]; ?> </option>
<?php
$sql = "SELECT * FROM education_details";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result))
{
$education_category = $row["id"];
$education_name= $row["name"];
?>
<option value='<?php echo $education_category?>'><?php echo $education_name;?></option>
<?php
}
?>
</select>

using php code within html to dynamically load a dropdown list

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.

Using SQL and PHP to Populate a HTML Select form

So I am currently having some difficulty using PHP to populate a select option on an HTML form. I need to have the select options filled with the data from my sql table and then I need to populate the selections into a different table in sql. First I will desribe the sql table that I am using. This is my first time using PHP and SQL so please keep that in mind if the code is completely off.
Note, I am able to connect to my database without any issues
SQL Data:
Table Name = "All Animals"
Column Name = "Group"
PHP Code:
$query = "SELECT *, dbo.All Animal.Group as allAnimal_Group
LEFT JOIN dbo.All Animal on dbo.Response.animalGroup = dbo.All Animal.Group
WHERE dbo.Response.animalGroup = %s";
$db->query($query, $Group);
$r = $db->fetch();
HTML and PHP Code:
<p>
<label for="animalGroup">Type</label>
<select name="Group" id="Group">
<option>Select a type:</option></select></p>
<?php
foreach($Group as $m)
{
?>
<option value="<?php echo $m['Group'];?>"><?php echo $m['animalGroup'];?></option>
<?php
}
?>
Thank you for looking and helping, I appreciate the assistance!
Your drop down list is closed before the php code. So edit it as below first.
<p>
<label for="animalGroup">Type</label>
<select name="Group" id="Group">
<option>Select a type:</option>
<?php
foreach($Group as $m)
{
?>
<option value="<?php echo $m['Group'];?>"><?php echo $m['animalGroup'];?></option>
<?php
}
?>
</select></p>
For the second part of your question, put this code inside html form and submit it to the server once the selection is made. So the complete code will be
<p>
<form action="your_file_name.php" method="post">
<label for="animalGroup">Type</label>
<select name="Group" id="Group">
<option>Select a type:</option>
<?php
foreach($Group as $m)
{
?>
<option value="<?php echo $m['Group'];?>"><?php echo $m['animalGroup'];?></option>
<?php
}
?>
</select>
<input type="submit" name="submitBttn" value="Submit">
</form></p>
in your_file_name.php file, write this to retrieve what is selected as,
$_POST['Group']
Then you can write sql code like "INSERT INTO table_name (column_name) VALUES ($_POST['Group'])"
More on html forms read this... http://php.net/manual/en/tutorial.forms.php
Update your query to use LIKE instead of = sign for wild character matching
$query = "SELECT *, dbo.'All Animals'.Group as allAnimal_Group
FROM dbo.'All Animals'
LEFT JOIN dbo.'All Animals' on dbo.Response.animalGroup = dbo.'All Animals'.Group
WHERE dbo.Response.animalGroup LIKE '%s'";
P.S You should change the foreach to use $r as iterator because you are storing database result in $r and not in $Group
foreach($r as $m){
}

AJAX + PHP self-generated fields producing blank results

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>';

Categories