How to data from tabe to combobox dynamically - php

how can i put the $CATEGORY dynamically so that whatever i click on the table it will retrieved in the combo box? (without settng its id to any number like 5 )
<?php
$CATEGORY = 5; //from DB table, consider 5 as category id for sample
$sql="SELECT tblcourse.id as id, tblcourse.course as course FROM tblcourse";
$result=mysql_query($sql) or die(mysql_error());
$options="";
while ($row=mysql_fetch_assoc($result)) {
$id=$row["id"];
$thing=$row["course"];
$isSel = ($CATEGORY == $id)?"selected":'';
$options.= " <OPTION VALUE='$id' $isSel>$thing</option>";
}
?>
My Combobox form code below :
<select name="cbocourse" style="height:35px; width:280px; background-color:#923227; box- shadow:1px 1px #FFF;color:#C90;" onClick="submitCATEGORY();">
<option value="<?php echo $CATEGORY; ?>">
<?php echo $options;?></option></select>

Your combobox code is wrong : you cannot parse a list of option into another super option, it means nothing. Just parse your $options between your select tags.
Just be sure to reload your page (or page fragment with AJAX for example) each time you call submitCATEGORY(), in order to regenerate your html combobox.
Your PHP code seems good.

Related

PHP/MySQL Auto select option based on previous page

I have a music database with a PHP front end where you can add/edit/delete artists, albums, tracks using the web client. The last real problem I have is getting a select box to automatically select an option I pass to the page.
Example:
On a page called 'createCD.php' I have this code:
echo "<td><a href=\"editCD.php?cdTitle=".rawurlencode($row['cdTitle'])."&cdID=$row[cdID]&artID=$row[artID]&cdGenre=".rawurlencode($row['cdGenre'])."&cdPrice=$row[cdPrice]\" </a>Edit</td>";`
This is used as a link to the next page, and collects all the information about an album in the database and sends in to a page called 'editCD.php'.
Now on this page, all the information is used to fill out the webpage as shown here (there is more but for the purposes of this post, only the first select box matters):
Artist Name:
<!-- dropdown with artist name -->
<?php
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'">'.$row['artName'].'</option>';
}
echo '</select>';
?>
<p>
Album Title:
<input id="cdTitle" type="text" name="cdTitle" value ="<?php echo htmlspecialchars($cdTitle); ?>" />
</p>
What I would like is for the "selected" option for 'artID' to be the value that is passed to the page. Using the associative array, I was able to display the 'artName' associated with the 'artID'. Currently, all the information about the album appears correctly apart from the 'artName' and it defaults to the first value. This is a problem as if a user simply clicks "Update" it will update the name to the default name, therefore changing the database entry by accident.
I know I need to be using
<option selected ...>
but I'm not sure on the syntax to use.
<?php
$artID = $_GET['artID']; // get the artID from the URL, you should do data validation
echo '<select name= "artID" id="artID">';
while ($row = mysqli_fetch_assoc($result)){
echo '<option value="'.$row['artID'].'"';
if ($artID == $row['artID']) echo ' selected'; // pre-select if $artID is the current artID
echo '>'.$row['artName'].'</option>';
}
echo '</select>';
?>
$artId = $_GET['artID'];
while ($row = mysqli_fetch_assoc($result)) {
$selected = $artId == $row['artID'] ? 'selected' : '';
echo '<option value="'.$row['artID'].'" '.$selected.'>'.$row['artName'].'</option>';
}
First you get the id via $_GET['artID']. (In a real scenario use intval or something to prevent sql injection)
Then check in the loop if the id from database is the same as the id from GET and when it is print "selected, else nothing.

Assign and return select option dynamically?

I have a form select which is generated based on results returned from a mysql query.
Q1) How do I assign a name identity (integer value) based on the teamID pull out of the database?
Q2) How could I then get the option selected and add it to a php variable which could then be used to update a table based on the users selection?
Below is the code I have so far for creating the dynamic drop down list, which get the results out of the database.
<?php
$data= mysql_query("SELECT * FROM teams
WHERE teamID NOT IN (
SELECT TeamID
FROM leagueInformation
WHERE leagueID = 1
)
") or die(mysql_query());
echo "<select name=\"team\" class=\"col-lg-12\" style=\"padding:10px; background:#e1e1e1;\">\n";
while($info = mysql_fetch_array( $data ))
{
$teamID = $info['teamID'];
echo "<option name=" . $team . " value=" . $teamID . ">" .$info['teamName'] . "</option>";
}
echo "</select>\n";
?>
Q1) How do I assign a name identity (integer value) based on the teamID pull out of the database?
This question is not so clear, but I think this is what you are trying to do?
<?php $data= mysql_query(
"SELECT * FROM teams WHERE teamID NOT IN (
SELECT TeamID
FROM leagueInformation
WHERE leagueID = 1)
") or die(mysql_query());
?>
<form name="teams_form" method="POST">
<select name="team" class="col-lg-12" style="...">
<?php while($info = mysql_fetch_array( $data )): ?>
<option value="<?php echo $info['teamID'] ?>">
<?php echo $info['teamName'] ?>
</option>
<?php endwhile; ?>
</select>
</form>
Q2) How could I then get the option selected and add it to a php variable which could then be used to update a table based on the users selection?
First you will need to wrap your select inside a form (like I did), then you can check the selected value like this:
if(isset($_POST['team']) && !empty['team']){
$selected_team = $_POST['team'];
mysql_query("Do what you want with the selected team");
}
Some notes about your code:
Avoid to use mysql_*, use mysqli_* or PDO, and always prevent SQL injections
<option> tags don't have name properties, and in this case $team is not defined
Embed PHP inside HTML, not HTML in PHP.
Your first question doesn't make sense to me yet, I'll update the answer when it does.
When the user submits the form, you can get the option selected using the $_GET or $_POST (depending your your form's method) variables.
Like this:
$teamId = $_POST['team'];
put everything in a <form/> with an action pointing to the page, and a method (get or post), then in the script get the variable by the <select/> name value reading $_GET or $_POST variables, and I quote the comment about the "name" in option as invalid attribute.

How to populate dependant select menus dynamically using jQuery, PHP and MySQL?

I have searched quite a bit on here about this topic. But I could not find a solution for my problem. I'd appreciate it a lot if you could help me, this is for a school project I am working on.
I have a database with a table ("Main_table") and columns including "sector" and "sub_sector". I want to have two select boxes, first one will load all the records from database in "sector" column and the second one will load all the records from database in "sub_sector" column depending on the selection value of the first select box. (For example: If I select "plastics" on the first select box, then second select box should be updated with sub_sector values where sector value is equal to "plastics").
I have managed to load the options values from database for the first select box but when I click on any selection, it does not load any option to the second select box. You can find the codes below. I did not put "sector_options.php" below, as it seems to work just fine.
index.html shown below:
<script>
$(document).ready(function() {
$('#filter_sector')
.load('/php/sector_options.php'); //This part works fine - uploads options to the first select box
$('#filter_sector').change(function() {
$('#filter_subsector').load('/php/subsector_options.php?filter_sector=' + $("#filter_sector").val()
} //This part does not work - no options on the second select box
);
});
</script>
<body>
<div id="sectors"><p>Sector:</p>
<select id="filter_sector" name="select_sector" multiple="multiple" size="5"> </select>
</div>
<div id="subsectors"><p>Sub Sector:</p>
<select id="filter_subsector" name="select_subsector" multiple="multiple" size="5"> <option value="" data-filter-type="" selected="selected">
-- Make a choice --</option>
</select>
</div>
</body>
</html>
sector_options.php shown below:
<?php
$link = mysqli_connect("*******", "*******","******","********") or die (mysql_error());
$query = "SELECT sector FROM Main_table ";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {
$options .= "<option value=\"".$row['sector']."\">".$row['sector']."</option>\n ";
}
echo $options;
?>
subsector_options.php shown below:
<?php
$link = mysqli_connect("********", "*****,"*******", "********") or die (mysql_error());
$Sectors = $_REQUEST['filter_sector'];
$query = "SELECT sub_sector FROM Main_table WHERE sector='$Sectors'";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {$options .= "<option value=\"".$row['sub_sector']."\">".$row['sub_sector']."</option>\n ";
}
echo $options;
?>
For completeness, the solutions were:
Check how AJAX operations are doing using a browser network monitor
Load AJAX fetcher scripts in a browser tag - in many cases they will render quite happily there, allowing them to be more easily debugged
AJAX scripts that return HTML for injection should only return that HTML, and not a full HTML document.

echo drop down menu onto a page

I have a drop down menu with two options in html, I also created a PHP script that checks what option from the drop down menu has been selected and based on the selection executes a mysql query to fetch data from database.
But I am also trying to echo out a new drop down menu with the results obtained from database and that is where the I am struggling because no errors are diaplayed but also no drop down menu is 'echoed' out onto the page.
HTML:
<?php require "course.php" ?>
<select id="workshop" name="workshop" onchange="return test();">
<option value="">Please select a Workshop</option>
<option value="Forex">Forex</option>
<option value="BinaryOptions">Binary Options</option>
</select>
PHP code:
$form['workshop'] = $_POST['workshop'];
$form['forex'] = $_POST['Forex'];
$form['binary'] = $_POST['Binary'];
//Retrieve Binary Workshops
if($form['workshop'] == 'Forex'){
$sql2 = "SELECT id, course, location FROM courses WHERE course LIKE '%Forex%' OR course LIKE '&forex%'";
$query2 = mysqli_query($link, $sql2);
echo "<select id='Forex' name='Forex' style='display: none'>";
while($result2 = mysqli_fetch_assoc($query2)){
echo "<option value=''>".$result2['course']."</option>";
}
echo "</select>";
echo '</br>';
}
Could someone point out a mistake I am doing or perhaps suggest where I could look for answers
you said $query2 is displaying value in print_r.so the only mistake i find in your code is display:none .
remove display:none
echo "<select id='Forex' name='Forex' style='display: none'>";
----------------------------------------------------------------------^

Drop down selection after saving

I do have a two drop downs called as source and campaign and these two drop down showing the data that are coming from the data base.i do have others input fields as well.my concern is that i want to save this data after filling it in the given input and selecting drop downs data it must be saved but after saving the data the drop downs must show the selection that i had selected while clicking on save button but it is showing default one.
my code is as follows:
This is for Source:
$result= mysql_query("SELECT * FROM infosources where kunnr = '".$_SESSION["kunnr"]."' order by sort_order asc");
$model["source"]=array();
while($row = mysql_fetch_array($result)){
array_push($model["source"],$row);
}
This is for campaign:
$result= mysql_query("SELECT * FROM s_campaigns WHERE kunnr ='".$_SESSION["kunnr"]."' and active = 'true' order by name asc");
$model["campaign"]=array();
while($row = mysql_fetch_array($result)){
array_push($model["campaign"],$row);
}
and my dropdown is as follows:
<select name="srcid"> <?php foreach($model["source"] as &$obj){?>
<option value=<?php echo $obj["srcid"];?>> <?php echo $obj["srcname"];?> </option>
<?php }?></select>
and the other drop down is
<select name="camp_id"> <?php foreach($model["campaign"] as &$obj){?>
<option <?php if($model["selected"]==$obj[""]){?>selected <?php }?> value=<?php echo $obj["id"];?>> <?php echo $obj["name"];?> </option>
<?php }?></select>
please suggest me on this...
for that you have to decide the value in view at time of refreshing your page
this is a very simplivied example and is just working if you send the form to the same file ... if you send the form to any other file or if you pass the $selectedCampId variable from the other file back to this html form
<?php
// fetch the database to get all possible campaings always... before form was saved and also afterwards
$result= mysql_query("SELECT * FROM s_campaigns WHERE kunnr ='".$_SESSION["kunnr"]."'
and active = 'true' order by name asc");
$model["campaign"]=array();
while($row = mysql_fetch_array($result)){
array_push($model["campaign"],$row);
}
// initiate $selectedCampId .... if the form is sent ... this variable will be filled with the campaign_id so that we know which option was selected... otherwise it wil remain empty..
$selectedCampId= '';
// if the save button was pushed, the form method is POST and the camp_id is not empty
// save the value of the camp_id input field to the variable so that in the next step
// we know which one was selected
if(!empty($_POST['camp_id'])){
// validate the input and save the data to database
// check which campaign id is selected and write it to variable
$selectedCampId= $_POST['camp_id'];
}
?>
<?php // the form method is POST otherwise use $_GET to fetch the camp_id after the form was sent ?>
<form method="post">
<select name="camp_id">
<?php foreach($model["campaign"] as &$obj): ?>
<option
<?php // if form is sent and $selectedCampId is not empty ... echo selected = "selected" ---- otherwise echo empty string ?>
<?php echo ($obj['id'] == $selectedCampId) ? 'selected = "selected"' : ""; ?>>
<?php echo $obj["name"];?>
</option>
<?php endforeach;?>
</select>
</form>

Categories