update a form having select option - php

I am having a form, which contains select option for data entry, (the options are fetching from MySQL database) if I want to update the form at later stage, is it possible to get the form select option as pre-selected?
Here I am showing the code for form having select options
<?php
$queryjob = "SELECT * FROM `job`";
$result2 = mysqli_query($con, $queryjob);
$options = "";
while($row2 = mysqli_fetch_array($result2))
{
$options = $options."<option>$row2[1]</option>";
}
?>
<tr>
<td ><div class='tabdata' align="right"> Name of Job/Survey: </div></td>
<td > <div class='tfieldz' align="right">
<select class='tfieldz' id="job_name" name="job_name" required='required'>
<?php echo $options;?>
</select></div>
</td>
</tr>

You can add a selected="" attribute to the option to have the option pre-selected.
Example would look like:
//You could use this in your loop
if($saved_value == $row[1]){
echo "<option selected>$row[1]</option>";
}else{
echo "<option>$row[1]</option>";
}

As I understand you are trying to set the default selected value of the selectbox. To set this value you can use following code:
/** The selectbox default value. This can come from database */
$selectbox_value = "selectbox default value";
while($row2 = mysqli_fetch_array($result2))
{
if ($selectbox_value == $row2[1]) $options = $options."<option SELECTED value='".$row2[1]."'>$row2[1]</option>";
else $options = $options."<option value='".$row2[1]."'>$row2[1]</option>";
}
In the above code the value attribute is added to the option tag. When the form is submitted, the value of the value attribute is sent to the server and stored in database. This stored value should be read from database and saved to $selectbox_value

Related

insert checkbox value into mysql database

I want to enroll the student and insert the student id into Mysql database after I check and submit the checkbox value, but I already tried so many ways but still cannot...
This is the php code
<?php
if (isset($_POST['submitxd'])) {
foreach ($_POST['enrol'] as $items) {
$insert = $link->query("INSERT INTO student_course(studentID) values ('$items')");}
}
?>
This is the html code
$result = $link->query("SELECT * FROM student WHERE programmeName = '$programme' AND intake = '$intake'");
while ($row = mysqli_fetch_array($result)) {
echo "<tr>
<td>".$row['studentID']."</td>
<td>".$row['studentName']."</td>
<td>".$row['studentGender']."</td>
<td>".$row['studentContact']."</td>
<td>
<input type='checkbox' name='enrol[]' value='".$row['studentID']."'>
</td>
</tr>";
}
check whether your array contains values or not:
echo "<pre>";
print_r($_POST['enrol']);
echo "</pre>";
if not, you should write html code properly i.e. check form tag and its action path carefully and before submitting the form, remember to check out the checkbox

Auto select drop-down in php form using mysql database

I am facing issue to set the Auto drop down in my php form.
while selecting the QC Type, it should automatically select QC Code from MySQL Database. At the moment, i am selecting it manually. Can anyone help.
php Form :
<tr>
<td align="right"><b>QC Code</b></td>
<td>
<select name="qc_code" >
<option>Select a QC Code</option>
<?php
$get_qc = "select * from qctype";
$run_qc = mysqli_query($con, $get_qc);
while ($row_qctype=mysqli_fetch_array($run_qc)){
$qccode_title = $row_qctype['qccode_title'];
echo "<option value='$qccode_title'>$qccode_title</option>";
}
Database : -
You should put the title into the value instead. This way the title will be displayed and the value will be submitted.
$qccode_title = $row_qctype['qccode_title'];
$qctype_title = $row_qctype['qctype_title'];
echo "<option value='$qctype_title'>$qccode_title</option>";

How to get HTML SELECT populated from Database

I'm trying to get an HTML SELECT field within a form to be populated from a database column. I can read the column fine, and can use fprint or echo to see the results. The problem is, I can't seem to get the array based on the column to appear as selections in the SELECT field. I'm able to produce a field with a pull-down selector, but the values aren't populated. How to I get the values from the Array into an HTML SELECT / OPTION field?
Here's a subset of the code I'm using:
<?php
$link = new mysqli("localhost","USER","PASSWORD", "DATABASE");
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if (!$link->set_charset("utf8"))
{
printf("Error loading character set utf8: %s\n", $link->error);
exit();
}
$role_sql = "SELECT role FROM lu_role";
$role_result = mysqli_query($link, $role_sql);
$options = "";
while($row1 = mysqli_fetch_array($role_result))
{
$options = $options."<option>$row1[1]</option>";
}
//Using the following to validate that I can get the query results in an array.
while ($row = $role_result->fetch_assoc())
{
printf($row["role"]);
}
?>
<form action="post.php" method="post">
<table class="table_600_reg">
<tr>
<td width="120">Father</td>
<td width="200" align="left">
<select>
<?php echo $options;?>
</select>
You may check your index in displaying your field. On your query, you only specified a field to be returned:
SELECT role FROM lu_role
So the index should start with '0' not '1'.
$options = $options."<option>$row1[0]</option>";
You may also use 'mysqli_fetch_assoc' so you can use $row1['role'] instead of relying on the index.
You are missing value="" here $options = $options."<option value='VALUE_HERE'>$row1[1]</option>";
And since you are selecting only one column it should be $row1[0] instead of $row1[1]
Try this :
$options = "";
while($row1 = mysqli_fetch_array($role_result))
{
$options .= "<option value='".$row1['role']."'>$row1['role']</option>";
}
and then can you able to use
<select>
<option value="">Select one</option>
<?php echo $options;?>
</select>
I would personally refer to the associative array values instead of the indexed values. If you later decided you wanted to pull more results from that table to manipulate other data, the index could change.
while ($row = $role_result->fetch_assoc()) {
$options .= "<option value='{$row['role']}'>{$row['role']}</option>";
}
you need to put your while statement inside the select tag
here is the code
<select>
<?php
while($row1 = mysqli_fetch_array($role_result))
{
$options = $options."<option>$row1[1]</option>";
echo '$options';
}
?>
</select>

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>

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