Populating a dropdown field using php - php

below code doesnot populate the list. i am trying populate a dropdown list from database but the below query doesnot populate the dropdownlist.
<form class="form-horizontal" role="form" method="post">
<div class="form-group">
<label for="inputLocation" class="col-sm-2 control-label">Location</label>
<div class="col-sm-4">
<select class="form-control" id="inputLocation" name="inputLocation">
<?php
$queryData = mysql_query("SELECT DISTINCT cat_name as cat_name FROM 'categories' ORDER BY `cat_name`");
$result = mysql_fetch_array(mysql_query($queryData)); //$result now has database tables
?>
<select name='cat_name'>
<?php
while($row = mysql_fetch_array($result))
{
?>
<option values=<?php echo($row['cat_name']); ?><?php echo($row['cat_name']); ?></option>
<?php
}
?> </select>
</div>
</div>
</form>

So you seem to be calling mysql_query and fetching the array twice...
$result = mysql_fetch_array(mysql_query($queryData);
Should be changed to
$result = mysql_fetch_array($queryData);
Then further down, change
while($row = mysql_fetch_array($result))
To...
foreach($result as $row)
You can always do
print_r($result);
To ensure you are getting data back from the query.
You also have two select tags, one of which isn't closed. Remove this top one
<select class="form-control" id="inputLocation" name="inputLocation">
Couple of other points to note:
The MySQL extension is depreciated, you should look into converting this query to MySQLi or PDO
You don't need brackets around an echo statement, just use
echo $variable;
Full edited code here
http://ideone.com/GASwcB

Related

Select values based on database result

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" >

isset() does not work properly by using include in PHP

I am a very beginner in programming PHP.
I have the following HTML code and two PHP code "include". I am not sure why ISSET() not firing at all.
If I remove the isset(){} it brings up the data perfectly fine...
but when I try with isset() it shows no data. Can anyone help?
<form action="functions/pos-getPrice.php"class="form-horizontal"
method="post">
<div class="form-group">
<label class="col-md-4 control-label">Item</label>
<div class="col-md-6 selectContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-list"></i>
</span>
<select name="item" id="item" class="form-control selectpicker" >
<option>Please select your item</option>
<?php include "functions/pos-getItems.php" ?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Price</label>
<div class="col-md-6 selectContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-list"></i>
</span>
<select name="price" class="form-control selectpicker" >
<option value="">Please select your price</option>
<?php include "functions/pos-getPrice.php" ?>
</select>
</div>
</div>
</form>
<?php
if(isset($_POST['item']) && $_POST['item'] == 'jacket') {
include "db-Info.php";
$res = mysqli_query($con, "select id, price, pointRequired from
tblPrice");
while($row = mysqli_fetch_array($res))
{
$price = $row['price'];
$pointRequired = $row['pointRequired'];
echo "<option value=\"".$row['id']."\">";
echo "Price: $price" ?> <?php echo "Point: $pointRequired";
echo "</option>";
}
}
?>
<?php
include "db-Info.php";
$res = mysqli_query($con, "select distinct item from tblPrice");
while($row = mysqli_fetch_array($res)){
$array = $row['item'];
echo "<option value=\"".$row['item']."\">";
echo $array;
echo "</option>";
}
?>
From what I can tell, I'm assuming your item list is loading correctly, and your price list is not? Are you expecting the price list to change when a user selects in item?
In this instance, there is no $_POST data when you load your page containing the form. Selecting an item in your dropdown does not send any kind of POST request causing the prices to change. Thus, at the time of page load, your price script is checking to see if $_POST["item"] is set and if that item is "jacket," which it is not at the time of page load. So no prices load, and that's that; the script doesn't keep checking what the item is after that.
If you're expecting prices to dynamically load based on the selected item, you'll either need to have an AJAX call that fetches the price options every time an item is selected, or you can preload all the price data upfront when the page loads, then use javascript to populate the price options on change of the item selector.

PHP echo in selection list with multiple selection options

I'm having a bit of struggle putting together a selection list in HTML where the options or values are being retrieved from a table in the database. I get the following result:
As you can see this is not my intention, I rather have all options in 1 Selection List, with multiple options clickable.
This is my HTML Code (Bootstrap Framework):
<div class="container-fluid well well-lg">
<?php while ($itemsrow = $query->fetch()) : ?>
<div class="form-group">
<label for="sel1">Select list:</label>
<select class="form-control" id="sel1">
<option><?php echo $itemsrow['Beschrijving']; ?></option>
The PHP Logic:
$conn = Db::getInstance();
$query = $conn->prepare("SELECT * FROM items WHERE user_id = $userID");
$query->execute();
Thanks in advance!
Currently, you're creating new elements inside the loop so yes, you will get a new select per iteration.
You should only keep the <option>-elements inside the loop:
<div class="container-fluid well well-lg">
<div class="form-group">
<label for="sel1">Select list:</label>
<select class="form-control" id="sel1">
<?php while ($itemsrow = $query->fetch()) : ?>
<option><?php echo $itemsrow['Beschrijving']; ?></option>
<?php endwhile; ?>
You should put your loop into <select> tag
<select class="form-control" id="sel1">
<?php while ($itemsrow = $query->fetch()) : ?>
<option><?php echo $itemsrow['Beschrijving']; ?></option>

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){
}

Categories