<?php
$sql=mysqli_query($mysqli,"select * from calls where eid='$aid'")or die(mysqli_error($mysqli));
while($row2=mysqli_fetch_assoc($sql))
{
?><select name='city'>
<option value="">Select City</option>
<?php
$c=explode(',', $row2['city']);
foreach ($c as $c1)
{
?>
<option value='$c1' <?php if(isset($_POST['search']) || isset($_POST['next'])|| isset($_POST['submit']))
{
if(($c==$c1))
{ echo 'Selected';}
}?>><?php echo $c1;?></option>"
<?php }
echo"</select>";
}
?>
calls table city is stored as comma separated array. I have successfully get it into drop-down box. Now I want that whenever I submit or page refresh it holds se selected drop-down value.
You should check for isset($_POST["city"]) && $_POST["city"] == $city
foreach ($cities as $city)
{
$selection = (isset($_POST["city"]) && $_POST["city"] == $city ? 'selected':'' );
echo ' <option value="'.$city.'" '.$selection.' >'.$city.'</option>';
}
You only need to compare the value of $c1 against its previous value returned by the form submit, after checking that this execution is the result of the form being posted.
<?php
$sql = "select * from calls where eid=?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $aid)
$stmt->execute();
$result = $stmt->get_result();
while($row2 = $result->fetch_assoc()) {
?>
<select name='city'>
<option value="">Select City</option>
<?php
$c=explode(',', $row2['city']);
foreach ($c as $c1) {
$sel = ''; // init value
if ( $_SERVER['REQUEST_METHOD'] == 'POST' && $c1 == $_POST['city'] ) {
$sel = "selected='selected'";
}
echo "<option $sel value='$c1' >$c1</option>";
}
echo "</select>";
}
?>
Related
I have this onchange event on php, if the user choose an option, it fetched the data that is connected on it. However, the page refreshes and the choice of the user disappear. Also, I cannot insert the data to database. I've tried add a form method="post" to the form attribute, but unfortunately it cannot fetch the data.
Thankyou in advance.
<?php
$dsn = 'mysql:host=localhost;dbname=admin';
$username = 'root';
$password = '';
try{
// Connect To MySQL Database
$con = new PDO($dsn,$username,$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo 'Not Connected '.$ex->getMessage();
}
$gradeassign = '';
$sectionassign = '';
function getPosts()
{
$posts = array();
$posts[3] = $_POST['sectionassign'];
$posts[4] = $_POST['gradeassign'];
return $posts;
}
if(isset($_POST['addfac']))
{
$data = getPosts();
$insertStmt = $con->prepare('INSERT INTO
facultyagain(sectionnumber,gradelevelassign)
VALUES(:sectionassign,:gradeassign)');
$insertStmt->execute(array(
':sectionassign'=> $data[3],
':gradeassign'=> $data[4],
));
if($insertStmt)
{
echo 'Data Inserted';
}
}
?>
<html>
<head>
<title>Country</title>
</head>
<body>
<form action="trial.php">
Select Your grade
<select name="gradeassign" onchange="this.form.submit()">
<option value="" disabled selected>--select--</option>
<option value="1">Grade 1</option>
<option value="2">Grade 2</option>
<option value="europe">Europe</option>
</select>
<?php
require 'connection.php';
if(isset($_GET["gradeassign"])){
$gradeassign=$_GET["gradeassign"];
$sql = "SELECT sectionassign FROM sections WHERE gradeassign='$gradeassign'";
$result = $con->query($sql);
echo "<select>";
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='$row[sectionassign]'>" . $row["sectionassign"]. " </option>";
}
} else { echo "<B>0 Results</B>"; }
echo "</select>";
}
?>
<BR>
<button id="addfac" name="addfac">Add Faculty</button>
</form>
</body>
</html>
You can also store the value in a variable and check to see if the option matches the variable. For example:
<option value="" disabled>--select--</option>
<option value="1" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "1") echo "checked"; ?>>Grade 1</option>
<option value="2" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "2") echo "checked"; ?>>Grade 2</option>
<option value="europe" <?php if(isset($_GET['gradeassign'])) && $_GET['gradeassign'] == "europe") echo "checked"; ?>>Europe</option>
The better way to do it would be to create the whole list with a loop. Bu this should work.
I need to select value dynamically using PHP in drop down list but in my case its not working as expected. I am explaining my code below.
<?php
$citySelected = "";
if(!isset($_GET['city'])){
$citySelected = 'selected="selected"';
}
?>
<select id="selectedLoc" name="selectedLoc" class="chosen-select form-control">
<option value="">Select City</option>
<option value="0" <?php echo $citySelected; ?>>Global</option>
<?php
foreach ($locationArr as $key => $value) {
$id = $value['id'];
$city = $value['city'];
$location = $value['location'];
$selected = "";
if(isset($_GET['city']) && $_GET['city']== $value['id']) {
$selected ='selected="selected"';
}
echo "<option value='$id' $selected>$location</option>";
}
?>
</select>
Here I need when there is any query string value then it will match with respective id and select that option and if there is no query string value at all then the global option will select.
Inside if condition ';' is missing. It should be like
if(isset($_GET['city']) && $_GET['city']== $value['id']){echo ' selected="selected"';}else{echo '';}
You can also use conditional operator for code simplicity, eg:-
<?php echo (isset($_GET['city']) && $_GET['city']== $value['id'])? ' selected="selected"':''; ?>
I have made many select box in PHP and I want to keep selected item as selected after refreshing the page. (when selecting same select box or another) here is my code.
$selectbox='<select class="form-control" name="estate_id" onchange="this.form.submit()" style="width: 200px" >';
$est_name = $client ->call('get_estate'); // call method from web services
$_SESSION['estname'] = array();
$_SESSION['estname'] = $est_name;
$count = count($_SESSION['estname']);
$i = 0;
foreach ($_SESSION['estname'] as $row)
{
$id = $_SESSION['estname'][$i]['est_id'];
$name = $_SESSION['estname'][$i]['est_name'];
if($id == isset($_POST['estate_id']))
{
$isSelected = ' selected="selected"';
}
else {
$isSelected = '';
}
$selectbox.= "<option value=".$id.$isSelected.">".$name."</option>";
$i++;
}
$selectbox.='</select>';
echo $selectbox;
<select name="name">
<option <?php if ($_GET['name'] == 'a') { ?>selected="true" <?php }; ?>value="a">a</option>
<option <?php if ($_GET['name'] == 'b') { ?>selected="true" <?php }; ?>value="b">b</option>
</select>
I know only this method. this method is assume that you know the values in all <option>
<select name="agama" id="agama">
<option value="Islam"<?php if ($rows['agama'] === 'Islam') echo ' selected="selected"'>Islam</option>
<option value="Khatolik"<?php if ($rows['agama'] === 'Khatolik') echo ' selected="selected"'>Khatolik</option>
<option value="Protestan"<?php if ($rows['agama'] === 'Protestan') echo ' selected="selected"'>Protestan</option>
<option value="Hindu"<?php if ($rows['agama'] === 'Hindu') echo ' selected="selected"'>Hindu</option>
<option value="Buddha"<?php if ($rows['agama'] === 'Buddha') echo ' selected="selected"'>Buddha</option>
<option value="Lain-Lain"<?php if ($rows['agama'] === 'Lain-Lain') echo ' selected="selected"'>Lain-Lain</option>
</select>
.... the above code is example from other people not mine.
but My case is the <option> is select from database too.
I have 2 table, oav_event and oav_album
the oav_album has foreign key (event_id) from oav_event table
I want to check if row['event_id'] from oav_album table is equal to option value (from oav_event table) if true, then set selected="selected"
while($row = mysqli_fetch_assoc($result)) { ?>
<option value="<?php echo $row['event_id']; ?>" >Event: <?php echo $row['event_date']; ?> </option>
<?php } ?>
the option will change depend on change in database table, so I don't know the value in option. How should I do?
<select name="event_id">
<?php
$sql = "SELECT * FROM oav_event";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
$selected = "";
if($row['event_id'] == $Yourmatchvalue)
{
$selected = "selected";
}
?>
<option value="<?php echo $row['event_id']; ?>" selected="<?php echo $selected; ?>" >Event: <?php echo $row['event_date']; ?> </option>
<?php } ?>
</select>
may this helps your. you need to replace $Yourmatchvalue variable with your variable.
You can use $_GET as the method on your form and pass the id of the record using it:
while($row = mysqli_fetch_assoc($result)) {
if (!empty($_GET['event_id']) && $row['event_id'] == $_GET['event_id']) {
$selected = 'selected = "selected"';
} else {
$selected = '';
}
echo '<option '.$selected.' value="'.$row["event_id"].'">'.$row["event_date"].'</option>';
}
Here is a solution,
$selected_value = 'Hindu'; // This will come from database
Change option tag with this
<option value="<?php echo $row['event_id']; ?>" <?php echo ($row['event_id'] == $selected_value) ? 'selected="selected"' : ''; ?> >Event: <?php echo $row['event_date']; ?> </option>
Create one function which will create options list like this:
function setDropdownValue($selectQueue_list,$selectedVal)
{
$queueVal = '';
$selectQueue_list_res=$db->query($selectQueue_list);
while($selectQueue_list_res_row=$db->fetchByAssoc($selectQueue_list_res))
{
$val = $selectQueue_list_res_row['id'];
$name = $selectQueue_list_res_row['name'];
if($val == $selectedVal)
{
$queueVal .= "<option value='$val' selected='selected' label='$name'>$name</option>";
}
else
{
$queueVal .= "<option value='$val' label='$name'>$name</option>";
}
}
return $queueVal;
}
Then create a query:
$get_value_query="SELECT id, name FROM table";
$dropdown_selected_value = !empty($dropdown_value) ? $dropdown_value: ''; // Pass value which you want to be selected in dropdown
Then call this function:
$dropdown_options = setDropdownValue($get_value_query, $dropdown_selected_value);
Later when you get dropdown options in $dropdown_options, use jquery to populate the dropdown, like this:
$('#dropdown_select_id').html("$dropdown_options");
Give it a try, and let me know.
I'm having trouble with my dynamic select forms. When the "subject" form is submitted it works perfectly, but when the "course" form is then submitted, the form seems to submit properly (localhost/page.php?subject=1&course=2), but it returns the option back to null so it isn't working with later php that is dependent on the course_id.
Header PHP:
<?php
$subject = $course = null;
$conn = mysql_connect('', '', '');
$db = mysql_select_db('',$conn);
if(isset($_GET["subject"]) && is_numeric($_GET["subject"]))
{
$subject = $_GET["subject"];
}
if(isset($_GET["course"]) && is_numeric($_GET["course"]))
{
$country = $_GET["course"];
}
?>
Javascript:
<script language="JavaScript">
function autoSubmit()
{
var formObject = document.forms['theForm'];
formObject.submit();
}
</script>
HTML Form:
<form name="theForm" method="get">
<select name="subject" onChange="autoSubmit();">
<option value="null">Select a Subject...</option>
<?php
$sql = "SELECT DISTINCT subj_name, subj_id FROM table1 ORDER BY subj_name";
$result = mysql_query($sql) or die ("couldn't execute query");
while($row = mysql_fetch_array($result))
{
echo ("<option value=\"$row[subj_id]\" " .
($subject == $row["subj_id"] ? " selected" : "") . ">$row[subj_name]</option>");
}
?>
</select>
<?php
if($subject != null && is_numeric($subject))
{
?>
<select name="course" onChange="autoSubmit();">
<option value="null">Select a Course...</option>
<?php
$sql = "SELECT DISTINCT course_id, course_name, subj_id FROM table1 WHERE subj_id = $subject";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo ("<option value=\"$row[course_id]\" " .
($course == $row["course_id"] ? " selected" : "") . ">$row[course_name]</option>");
}
?>
</select>
<?php
}
?>
</form>
In these lines "selected" should only be set if $subject and $course are not passed in callback request:
<option value="null" selected="selected">Select a Subject...</option>
...
<option value="null" selected="selected">Select a Course...</option>
Otherwise, you'll get two options marked as selected in each dropdowns. This cause to bug.
<pre>
if(isset($_GET["course"]) && is_numeric($_GET["course"]))
{
$country = $_GET["course"];
}
</pre>
Here, you are setting a $country variable instead of $course.
**Use this one**
$course= $_GET["course"];
I found the error: $country in line 14 needs to be $course:
if(isset($_GET["course"]) && is_numeric($_GET["course"]))
{
$course = $_GET["course"];
}
?>