Drop down selection after saving - php

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>

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.

Show existing value as pre-selected in drop down, radio buttons and checkboxes fields

I have a network that I am building which groups freelancers together and allows potential customers to browse a profile containing their details.
In my database I store some values that the user will enter via a form using drop down or radio/checkbox fields. Through an edit page they can amend that data.
I'm struggling with how to get those fields pre-populated (if the value exists in the DB) with the value they've already made, probably at the time of creating their profile. I have managed to do it with the regular text/input fields by echoing out the column value as a form field value but can't figure out how to achieve it with these other fields.
UPDATE: I need to pull the value from the database and have the form fields show that as the pre-selected/default entry.
If I leave them blank it means the user will overwrite any existing data with nothing and in erase anything they've entered for that field before.
An example drop down field is below;
<div class="item-content">
<div>Experience</div>
<select class="form-control" name="profile_experience" id="profile_experience">
<option value="1">Amateur</option>
<option value="2">Semi Professional</option>
<option value="3">Professional</option>
</select>
</div>
I'm fetching the values with the following;
<?php
$id=$_SESSION['user']['id'];
$result = $db->prepare("SELECT * FROM profiles WHERE user_id= :userid");
$result->bindParam(':userid', $id);
$result->execute();
for($i=0; $currentprofile = $result->fetch(); $i++){
?>
<!--FORM HERE-->
<?php
}
?>
Retrieve and stote the stored values
<?php
$query = "SELECT id FROM Tablename WHERE YOUR_CONDITION";
$result = mysqli_query($connection, $query);
if (mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
$selectedOption = $row['id'];
}
else
{
$selectedOption = ''; // Your default selection of $cc
}
$profile_experience_array = array(1=>'Amateur',
2=>'Semi Professional',
3=>'Professional');
?>
The below code displays all the options of profile_experience_array. $key will check with the database value ($selectedOption) and that text will get selected by default.
<div class="item-content">
<div>Experience</div>
<select class="form-control" name="profile_experience" id="profile_experience">
<option value="0">Select</option>
<?php
foreach ($profile_experience_array as $key => $text)
{
if ($key == $selectedOption)
{
echo '<option value="'.$key.'" selected="selected">'.trim($text).'</option>';
}
else
{
echo '<option value="'.$key.'">'.trim($text).'</option>';
}
}
?>
</select>
</div>

How to data from tabe to combobox dynamically

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.

How to use assign html select value to a php variable

<select name="parentgroup" type="text" id="select2" onchange="this.form.submit();">
<?php
echo "<option value=\"0\">All Users</option>";
$result = mysql_query("select * from login WHERE stato=1");
while ($myresults = mysql_fetch_array($result))
{
$username = $myresults['user_name'];
echo "<option value=\"".$username."\" ";
echo $username== $parentgroupid ? " selected" : "";
echo ">".$username."</option>";
}
?>
</select>
Hi...am supposed to use the first element in <select> which is <option value=\"0\">All Users</option> to fetch values from a mysql database.
I want to now how you can assign this to a variable and use it just like $parentgroupid
When you submit the form (which presumably exists since you are referencing it from your JavaScript): Get the value from $_GET['name_of_form_control'] in the document referenced by the action attribute of the form.
When you submit the form, depending on the method specified in the form ("GET" or "POST"), the value will be in either the $_GET or $_POST arrays on the page to which you are submitting. You can retrieve the value by name (the name of the control):
$parentgroupid = $_GET['parentgroup'];
or
$parentgroupid = $_POST['parentgroup'];

get value of select box without submitting a form

hi i want to get the value the user selected from the dropdown menu without submitting a form and save it in a php variable any ideas ??
<select name="car" value="Select" size="1">
<?php
$sql = "SELECT fullname FROM users";
$result = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_array($result))
{
$name=$row["fullname"];
$options .= '<option value="'.$name.'">'.$name.'</option>';
}
?>
<?php echo $options; ?>
</option>
</select>
I don't think you fully understand how PHP works server side, but to get the value of a dropdown menu without submitting it you'll need Javascript (jQuery makes everything easier). From there you just send an AJAX request using JSON as data format and retrieve it from PHP with json_decode.

Categories