Using SQL and PHP to Populate a HTML Select form - php

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

Related

How can I echo SQL data from database table into a <select> form? [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 3 years ago.
i would like to echo some SQL data into a <select> form with each as a different row from the table.
i have a table:-
repair (repair_id , date , machine_name ,Machine_vin , request , adresss);
and i would like to have the Machine_vin numbers to come in the select options.. and each time one is removed or added it reflects in the option.
am stumped on code, only have:
<?php
$sql = "select * from repair";
$res = mysqli_query($conn,$sql);
$selectResult="";
while($list = mysqli_fetch_array($res)){
$Machine_vin = $list['Machine_vin'];
$selectResult.="<option value="$Machine_vin">$Machine_vin</option>";
?>
get a Parse error: syntax error, unexpected '$Machine_vin'
how do i reflect the machine_vins in the <select> option.
<?php
$sql = "select * from repair";
$res = mysqli_query($conn,$sql);
$selectResult="";
while($list = mysqli_fetch_array($res)){
$Machine_vin = $list['Machine_vin'];
$selectResult.="<option value='$Machine_vin'>$Machine_vin</option>";
?>
<form method='post' action='#'>
<select name="course">
<option value="0">Please Select Option</option>
<?php echo $Machine_vin; ?>
</select>
</form>
I think you should update your question with something you have tried. Even a piece of code you tried to accomplish your goal.When you need to fetch data and add those data into a drop down you can follow below steps.
1.Fetch data from DB.
2.Assign each of data into drop down options with a while loop
<div class="form-group">
<label class="col-md-2 control-label">Machine_vin numbers </label>
<div class="col-md-4">
<select class="form-control" name="machine_vin" required>
<option value="0" selected disabled>Select the type of Machine vin number</option>
<?php
//fetch data from db
$sql_machine_vin = ' SELECT * FROM repair';
// query the sql with db connection
$result_machine_vin = mysqli_query($conn,$sql_machine_vin);
//loop the result
while($row_machine_vin =mysqli_fetch_array($result_machine_vin)){
?>
<option value="<?=$row_machine_vin['Machine_vin'];?>" >
<?=$row_machine_vin['Machine_vin'];?> ></option>
<?php
}
?>
</select>
</div>>
Assuming you are new to PHP and MySQL
for starters you can start reading this:
https://www.php.net/manual/en/book.mysqli.php
To get the data and parse it through PHP is like this:
https://www.php.net/manual/en/mysqli-result.fetch-assoc.php
Then you play with your output buffer ECHO scripts and render the tags you want them to put in to.

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.

Select all users with specific MySql request PHP

I'm coding a feature in PHP, it's a search engine.
<form action="result" method="POST">
<select name="instrument" id="instrument">
<option value="all">All instrument</option>
<option value="1">Guitar</option>
<option value="2">Bass</option>
<option value="3">Battery</option>
<option value="4">Singer</option>
</select>
<select name="theme" id="theme">
<option value="all">All themes</option>
<option value="1">Metal</option>
<option value="2">Jazz</option>
<option value="3">Rock</option>
<option value="4">Blues</option>
</select>
<input type="submit" value="search" />
</form>
I already code this search engine like this and it works
<?php
if(isset($_POST)) {
$theme = $_POST['theme'];
$instrument = $_POST['instrument'];
$req_search = $bdd->query("SELECT * FROM user,theme,instrument WHERE theme.theme_id = user.user_theme AND instrument.instrument_id = user.user_instrument AND theme_id =".$theme." AND instrument_id =".$instrument);
if($req_search->rowCount()>0) {
while($search = $req_search->fetch()) {
?>
<p><?php echo $search['user_username']; ?></p>
<?php
}
$req_search->closeCursor();
} else {
echo "Users not found";
}
}
?>
You can find users who is matching with those options (without All instrument and All themes.
Everything is stored into a MySql database.
However when I click on All themes and All instrument. I want to update my select request. Like if I select All instrument and All themes I want to display every users. Or if I select All instrument and Metal, I want to display all users listening to metal and playing whatever instrument.
Thanks for your help !
You can construct your query to be conditional depending on whether $theme and $instrument have values:
$query = "SELECT * FROM user,theme,instrument
WHERE theme.theme_id = user.user_theme
AND instrument.instrument_id = user.user_instrument".
($theme!="" ? " AND theme_id='$theme'" : "").
($instrument!="" ? " AND instrument_id='$instrument'" : "");
$req_search = $bdd->query($query);
That said, you should look into PDO Prepared Statements and Placeholders, because all this would take is someone to fiddle around with the DOM to perform some MySQL Injection.

Populating a dropdown field using 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

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