dropdown select value resets after onchange - php

I am trying to create a dynamic drop-down using php/mysql. For some reason the selected value does not stay selected. The drop-down reset to the initial value. The selected value is used to populate a table on the same php page.
<form action="" method="get">
<select name="user" onchange="this.form.submit();">
<?php
do {
?>
<option value="<?php echo $row["userid"]?>" selected="selected"><?php echo $row["display_name"]?></option>
<?php
} while ($row = mysqli_fetch_assoc($result));
$rows = mysqli_num_rows($result);
if($rows > 0) {
mysqli_data_seek($result, 0);
$row = mysqli_fetch_assoc($result);
}
?>
</select>

You have to add a logic in your code for that.
First when you get data from form, save your dropdown value in a variable.
eg. $user = $_GET['user'];
Now make the following changes in your code.
<form action="" method="get">
<select name="user" onchange="this.form.submit();">
<?php
do {
?>
<option value="<?php echo $row['userid']?>" <?php if($user == $row['user_id']) { echo 'selected="selected"' } ?> >
<?php echo $row["display_name"]?></option>
<?php
} while ($row = mysqli_fetch_assoc($result));
$rows = mysqli_num_rows($result);
if($rows > 0) {
mysqli_data_seek($result, 0);
$row = mysqli_fetch_assoc($result);
}
?>
</select>

Related

Keep the value selected after fetching the data and query to insert it into database

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.

give name to each option value

I have a table with id, header, etc. Would like to make a give a name from header column to dropdown list to each value. Now its only shows value, which is very uncomfortable :
<form method="POST" enctype="multipart/form-data" action ="uploadext.php">
<?php require_once('uploadext.php'); ?>
<div class="col-md-6"><input type="file" name="fileToUploadgp"></div>
<div class="col-md-6"><input type="file" name="fileToUploadpro"><br>
<?php
$dbc = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$query = "SELECT id, header FROM done_add";
$query1="SELECT header FROM done_add";
$data = mysqli_query($dbc, $query);
$data1=mysqli_query($dbc, $query1);
$array=[];
while ($row = mysqli_fetch_array($data)) {
$arrayid[] = $row['id'];
$arrayhead[]=$row['header'];
}
?>
<select name="selectlink">
<?php foreach ($arrayid as $arr) {?>
<option value = "<?php print($arr)?>"
} ?><?php print($arr) ?></option>
<?php } ?>
</select>
<input type="submit" value="Отправить файлы" name="submita">
</div>
</form>
(sorry for bad english)
change the way you store your data in $array:
while ($row = mysqli_fetch_array($data)) {
$option = [];
$option['id'] = $row['id'];
$option['header'] = $row['header']
$array[] = $option;
}
every $option in $array will have and id and a header, then you can simply:
<select name="selectlink">
<?php foreach ($array as $option) {?>
<option value = "<?php echo $option['id'];?>"
} ?><?php echo $option['header'];?></option>
<?php } ?>
</select>

Calling mysql procedure using drop down list in PHP

I have my drop down form like this:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
<p>Get a Report of each Gene:<br>
<select name="Prot_Id">
<!--option value="" selected disabled>Select a rating</option-->
<option value="" selected disabled></option>
<option value="chr">chr12:111,843,752-111,889,427</option>
<option value="chr">chr19:17,186,591-17,324,104</option>
<option value="chr">chr2:102,927,962-103,015,21</option>
<option value="chr">chr2:204,732,511-204,738,683</option>
<option value="chr">chr4:123,372,626-123,377,650</option>
<option value="chr">chr4:123,533,783-123,542,212</option>
<option value="chr">chr6:159,456,027-159,466,184</option>
</select>
</p>
<input type="submit" name="submit1" value="Go" />
</form>
I have one MySQL stored procedure Chrome_Seq with one input parameter (eg:chr2:102,927,962-103,015,21 it's the display name for the drop down box).. Now I am writing a PHP page to call this procedure and show the result as table. Here is my PHP code:
<?php
if (isset($_POST['chr'])) {
echo "hi 11";
$id=$_POST['chr'];
echo "<table>";
//connect to database
$connection = mysqli_connect("localhost", "root", "", "KCC_Celiac_Disease");
//run the store proc
echo "hello";
$query= "call Chromo_Seq(".'"'.$id.'")';
$result = mysqli_query($connection, $query) or die("Query fail: " . mysqli_error());
//loop the result set
echo "<tbody>";
// point to the beginning of the array
$check = mysqli_data_seek($result, 0);
$rownew = mysqli_fetch_assoc($result);
foreach($rownew as $k => $v ) {
echo "<th>".$k."</th>";
}
$check = mysqli_data_seek($result, 0);
while ($rownew = mysqli_fetch_assoc($result)) {
echo "<tr>";
foreach($rownew as $k => $v) {
echo "<td>".$v."</td>";
}
echo "</tr>"."<br>";
}
echo "</tbody></table>";
}
?>
Whenever I select a value from dropdown it should run the procedure with that parameter and return the value but I am not getting any result in my output. It's blank.

Setting selected option in drop-down box

My SELECT looks like the following:
<?php
$query = "SELECT * FROM Rec_SW2_Rel AS a JOIN SW2 b ON a.Sbj_ID = b.IDsbj GROUP BY a.Sbj_ID ORDER BY b.Descriptor";
$result = mysql_query($query);
?>
<select name="country" onchange="getState(this.value)">
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
?>
<option value="<?php echo $line['Sbj_ID']; ?>">
<?php echo $line['Descriptor']; ?>
</option>
<?php
}
mysql_close();
?>
</select>
Querying the DB and setting up the drop-down works. The problem is that the value listed first isn't automatically selected. If a user wants to use it, for further navigation, they must first select a different one and then select the first once again.
I couldn't alter the values in the DB. If I insert selected='selected' it returns the last value of the result set, but always without being selected.
You maybe want this? First selected option when the form is loaded is blank.
<select name="country" onchange="getState(this.value)">
<option value=""></option>
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
or select the selected data from the database? selected column with selected value.
<select name="country" onchange="getState(this.value)">
<?php
$first = true;
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
?>
<option value="<?php echo $line['Sbj_ID']; ?>" <?php echo ($line['selected']=='selected') ? 'selected="selected"' : '' ; ?>>
you can test with respect to $line['Sbj_ID'] if this is = to the value you want by default
<?php
$query = "SELECT * FROM Rec_SW2_Rel AS a JOIN SW2 b ON a.Sbj_ID = b.IDsbj GROUP BY a.Sbj_ID ORDER BY b.Descriptor";
$result = mysql_query($query);
?>
<select name="country" onchange="getState(this.value)">
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
?>
<option value="<?php echo $line['Sbj_ID']; ?>" <?php if($line['Sbj_ID']==value_you_want_selected){?>selected<?php } ?>>
<?php echo $line['Descriptor']; ?>
</option>
<?php
$i++; }
mysql_close();
?>

How to show selected value of dropdown list from database in php

How do I show the selected value of a dropdown list from my mysql database. The dropdown list is dependent to my Category dropdown list. These are the codes:
<?php $id = $_GET["id"];
if(!$pupcon){
die(mysql_error());
}
mysql_select_db($database_pupcon, $pupcon);
$getDropdown2 = mysql_query("select * from tblitemname where CategoryID = $id");
while($row = mysql_fetch_array($getDropdown2)){
echo "<option value=\"".$row["ItemID"]."\">".$row["Item_Name"]."</option>";
} ?>
Here are the codes for the first dropdown list (Category) which populates the Item Name dropdown.
<select name="Category" id="Category" class="field select large" onChange="loadXMLDoc(this.value);">
<?php do { ?>
<option value="<?php echo $row_Recordset1['CategoryID']?>"<?php if (!(strcmp($row_Recordset1['CategoryID'], $row_editRecordset['CategoryID']))) {echo "selected=\"selected\"";} ?>><?php echo $row_Recordset1['CategoryName']?></option>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); $rows = mysql_num_rows($Recordset1); if($rows > 0) {
mysql_data_seek($Recordset1, 0);
$row_Recordset1 = mysql_fetch_assoc($Recordset1);}?>
</select>
While you're listing out the drop down options, you can check to see if the current ItemID matches the passed id value. If it matches, throw a selected="selected" in there. Try:
$selected = ($row['ItemID'] == $id);
echo "<option value=\"".$row["ItemID"]."\" ".($selected ? " selected=\"selected\"":"").">".$row["Item_Name"]."</option>";
EDIT
I tried to clean up the code some...not sure why you're using a do...while because $row_Recordset1 wouldn't be available on the first iteration.
<select name="Category" id="Category" class="field select large" onChange="loadXMLDoc(this.value);">
<?php
while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)) {
?>
<option value="<?php echo $row_Recordset1['CategoryID']; ?>"<?php if (!(strcmp($row_Recordset1['CategoryID'], $row_editRecordset['CategoryID']))) { echo " selected=\"selected\""; } ?>>
<?php echo $row_Recordset1['CategoryName']; ?>
</option>
<?php
}
?>
</select>
you can use this code inside while
$selected=$row["ItemID"]==$id ?'Selected':'';
echo "<option value=\"".$row["ItemID"]."\" {$selected} >".$row["Item_Name"]."</option>";;

Categories