Get text of select box in php page - php

I have select box in PHP and want text selected item of that:
<form action="" method="get" target="" dir="rtl" class="w3-container">
<?php
echo " <select id='p1' name='p1' >";
echo "<option value='*'>Choose person</option>";
sql code
$result2 = mysql_query($query2,$con);
while($row2 = mysql_fetch_array($result2))
{
$row2['name'];
echo "<option value='".$row2['id']."'>".$row2['name']."</option>";
}
echo " </select>";
mysql_close($con);
?>
<input class="w3-btn w3-hover-yellow" name="" type="submit" value="جستجو">
</form>
<?php
if(isset($_GET['p1']) and $_GET['p1'] != "*")
{
if ($name_insert=trim($_GET["p1"]))
{
if ($strWhere == ""){
$strWhere .= "name_insert='".trim($name_insert)."' ";
$getPage .= "&name_insert=".($name_insert);}
else{
$strWhere .= " and name_insert='".trim($name_insert)."' ";
$getPage .= "&name_insert=".($name_insert);}
}
}
?>
I want code that get text of select box in $name_insert. This code gets value of that.

You can use javascript and save selected option text in a hidden field.
Example
<form action="" method="POST">
<select id="test" onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
<option value="1">Test One</option>
<option value="2">Test Two</option>
</select>
<input type="hidden" name="test_text" id="text_content" value="" />
</form>
PHP
$getOptionText = $_POST['test_text'];
Replace your code with this code
<form action="" method="get" target="" dir="rtl" class="w3-container">
<select id='p1' name='p1' onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
<option value='*'>Choose person</option>
<?php
$result2 = mysql_query($query2,$con);
while($row2 = mysql_fetch_array($result2))
{
echo "<option value='".$row2['id']."'>".$row2['name']."</option>";
}
mysql_close($con);
?>
</select>
<input type="hidden" name="test_text" id="text_content" value="" />
<input class="w3-btn w3-hover-yellow" name="" type="submit" value="جستجو">
</form>
<?php
if(isset($_GET['p1']) and $_GET['p1'] != "*")
{
$getValueOfText = $_GET['test_text'];
echo $getValueOfText;
if ($name_insert=trim($_GET["p1"]))
{
if ($strWhere == ""){
$strWhere .= "name_insert='".trim($name_insert)."' ";
$getPage .= "&name_insert=".($name_insert);}
else{
$strWhere .= " and name_insert='".trim($name_insert)."' ";
$getPage .= "&name_insert=".($name_insert);}
}
}
?>

Related

How to create checkboxs that fetch from database and pass on value

I am new to php and can not turn a row into a checkbox field that passes onto a separate page.
if ($result = $db->query($sql) ) {
//*start of original
if ($result->num_rows > 0) {
?>
<!-- <form action="Confirmation.php" method="post"> -->
<form action="Payment.php" method="post">
<label for="PatientID">Choose the Patient you wish to register for:</label>
<select name="PatientID" id="">
<option value="" disabled>Please select a patient to enroll:</option>
<!-- <option value="All">All Patients</option> -->
<?php
while($result = fetch_assoc($result)) {
echo "<input type='checkbox' value='{$row['PatientID']}'>" . $row['PatientName'] . '</br>';
}
//
//while ($row=$result->fetch_assoc()) {
?>
//<option value="<?=$row['PatientID'];?>"> <?=$row['PatientName']?></option>
//*/ <?php
//}
echo '</select><input type= "submit" class="myButton" name="submit" value="Register Now" /></form>';
} else {
echo "There are no patients currently available for registration." ;
$rosterListFail = true;
}
} else {
$message = $db->error;
// echo $message;
}
//*/
//}
?>

Database driven select box being empty on submit

I am trying to submit a form value in a database with php. In form a select box value comes from database.
<?php include_once 'header.php';
$sql="SELECT uid,name FROM emitra_basic where block='$user'";
$result = $conn->query($sql);
//form validion
if(isset($_POST['submit']))
{
$eid =$_POST["eid"];
if($eid=="blank")
{
$flag=1;
$idErr="please Select E-MITRA";
}
$miatm =trim($_POST["miatm"]);
if(empty($miatm) || !preg_match("/^[a-zA-Z0-9 ]*$/",$miatm)) {
$flag=1;
$miErr="Please Enter Valid Id";
}
.............like this
if($flag==0)
{
$sqll="insert into **********";
}
//my form is
<form id="basic" method="post" name="basic">
<select class="select-style gender" name="eid">
<option value="blank">Please Select E-MITRA ID</option>
<?php
while($row=mysqli_fetch_array($result))
{
?>
<option value="<?php echo $row['uid']; ?>"><?php echo $row['uid']." (" . $row['name'] .")"; ?></option>
<?php
}
?>
</select>
<p class="contact"><label for="bid">Micro-ATM Serial No</label></p>
<input type="text" name="miatm" value ="<?php if (isset($miatm)) echo $miatm; ?>" /> <?php echo $miErr; ?>
<p class="contact"><label for="bid">Micro-ATM TID No</label></p>
<input type="text" name="tid" value ="<?php if (isset($tid)) echo $tid; ?>" /> <?php echo $tiErr; ?>
<input class="buttom" name="submit" id="submit" value="Add Me" type="submit">
Its seems Ok.but when i tried to submit the form if some of one field remain empty then its show blank value in select box.
how can i remain the same selected value in select box even if textbox remain empty.
You need to retain the value of drop down after form submit.
User selected attribute of select option.
<?php
if (isset($_POST['submit'])) {
$eid =$_POST["eid"];
if ($eid=="blank") {
$flag=1;
$idErr="please Select E-MITRA";
}
}
$sql="SELECT uid,name FROM emitra_basic where block='$user'";
$result = $conn->query($sql);
?>
<select class="select-style gender" name="eid">
<option value="blank">Please Select E-MITRA ID</option>
<?php
while($row=mysqli_fetch_array($result)) {
$selected = (isset($_POST["eid"]) && $_POST["eid"] == $row['uid']) ? 'selected="selected"' : '';
?>
<option value="<?php echo $row['uid']; ?>" <?php echo $selected;?>><?php echo $row['uid']." (" . $row['name'] .")"; ?></option>
<?php
}
?>
</select>
You need to use selected="" or selected="selected" after submission in your select tag as a attribute as:
<?
$sql="SELECT uid,name FROM emitra_basic where block='$user'";
$result = $conn->query($sql);
?>
<select class="select-style gender" name="eid">
<option value="blank">Please Select E-MITRA ID</option>
<?php
while($row=mysqli_fetch_array($result))
{
$selected = ((isset($_POST["eid"]) && $_POST["eid"] == $row['uid']) ? 'selected=""' : '');
?>
<option <?=$selected?> value="<?php echo $row['uid']; ?>"><?php echo $row['uid']." (" . $row['name'] .")"; ?></option>
<?php
}
if(isset($_POST['submit']))
{
$eid = $_POST["eid"];
if($eid=="blank")
{
$flag=1;
$idErr="please Select E-MITRA";
}
?>
</select>
Side Note:
In your question ist two lines are not inside the php, i hope this is type error.

Populating select box with existing value

I have created a form which allows users to edit existing data within a database, I pull information from one page to the next to populate text boxes and select boxes. I have managed to populate the select box with the correct value but when the update statement goes through it deletes or doesn't recognize the pre-existing value. Can anyone help?
if (isset($_POST['submit'])) {
// Process the form
if (empty($errors)) {
$id = $brand["brandId"];
$brandName = mysql_prep($_POST["brandName"]);
$brandCategory = mysql_prep($_POST["brandCategory"]);
$brandKeyword = mysql_prep($_POST["brandKeyword"]);
$addedBy = mysql_prep($_SESSION['username']);
$query = "UPDATE brands SET ";
$query .= "brandName = '{$brandName}', ";
$query .= "brandCategory = '{$brandCategory}', ";
$query .= "brandKeyword = '{$brandKeyword}', ";
$query .= "addedBy = '{$addedBy}', ";
$query .= "dateTime = CURRENT_TIMESTAMP ";
$query .= "WHERE brandId = '{$id}' ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
// Success
$_SESSION["message"] = "Brand updated.";
redirect_to("search.php");
} else {
// Failure
$_SESSION["message"] = "Brand update failed.";
}
}
} else {
// This is probably a GET request
} // end: if (isset($_POST['submit']))
?>
<?php $layout_context = "user"; ?>
<?php include("../includes/layouts/header.php"); ?>
<?php include("../includes/layouts/navigation.php"); ?>
<div class="section">
<div id="message">
<?php echo message(); ?>
<?php echo form_errors($errors); ?>
</div>
<form id="edit_brands" action="edit_brands.php?id=<?php echo urlencode($brand["brandId"]); ?>" method="post">
<h2>Edit Brand Information: <?php echo htmlentities($brand["brandName"]);?></h2>
<p>
<label for="bname">Brand Name:</label>
<input class="textbox" id="bname" type="text" name="brandName" value="<?php echo htmlentities($brand["brandName"]); ?>" autofocus/>
</p>
<p>
<label for="bcategory">Brand Category:</label>
<select class="textbox" id="bcategory" type="text" name="brandCategory">
<option value=""><?php echo htmlentities($brand["brandCategory"]); ?></option>
<option value="Animation">Animation</option>
<option value="Automotive">Automotive</option>
<option value="Beauty and Fashion">Beauty & Fashion</option>
<option value="Comedy">Comedy</option>
<option value="Cooking and Health">Cooking & Health</option>
<option value="DIY">DIY</option>
<option value="Fashion">Fashion</option>
<option value="Film and Entertainment">Film & Entertainment</option>
<option value="Food and Drink">Food & Drink</option>
<option value="Gaming">Gaming</option>
<option value="Lifestyle">Lifestyle</option>
<option value="Music">Music</option>
<option value="News and Politics">News & Politics</option>
<option value="Science&Education">Science & Education</option>
<option value="Sports">Sports</option>
<option value="Technology">Technology</option>
<option value="Television">Television</option>
</select>
</p>
<p>
<label for="bkeyword">Brand Keyword:</label>
<textarea class="FormElement" id="bkeyword" name="brandKeyword" id="brandKeyword" placeholder=""><?php echo htmlentities($brand["brandKeyword"]); ?></textarea>
</p>
<p>
<input type="submit" class="button" name="submit" value="Edit Brand" onclick="return confirm('Do you wish to edit brand?');"/>
</p>
<p>
Cancel
</p>
</form>
</div>
</div>
The best way is to build the select from an array.
For instance:
<?php
$array = array('Animation', 'Automotive', 'Beauty and Fashion ', ...);
echo '<select class="textbox" id="bcategory" type="text" name="brandCategory">';
foreach ($array as $value){
if($value == htmlentities($brand["brandCategory"]){
echo '<option value='.$value.' selected>'.$value.'</option>';
}else{
echo '<option value='.$value.'>'.$value.'</option>';
}
}
echo '</select>;
This way you can check if the value in the array is the same that the one recieved by post and then add the selected attribute to the option tag.

Save selected option from a dropdown box

<form method="post">
<select name="select_employee" id="select_employee">
<?php $allemp=$this->AllEmployees; ?>
<option selected value="">Select an employee..</option>
<?php foreach($allemp as $row){ echo "<option value=".$row[ 'Id']. ">".$row[ 'Etunimi']. " - ". $row[ 'Sukunimi']. "</option>"; } ?>
</select>
<input type="hidden" name="send" value="namesent">
<input type="submit" value="submit" id="button">
</form>
<br/>
<br/>
When I submit this form, I stay on the same page, but I want a the same time to keep the option selected previously option visible.. How can I do that?
I tried:
document.getElementById('select_employee').value = "<?php echo $_GET['select_employee'];?>";
But it did not work..
here:
foreach($allemp as $row){
echo "<option " . (isset($_POST['select_employee']) && $_POST['select_employee'] == $row['Id'] ? ' selected ' : '') . " value=".$row['Id'].">".$row['Etunimi']." - ".$row['Sukunimi']."</option>";
}
Try this :
$selected = ($row['Id'] == $_REQUEST['select_employee'])?'selected="selected"':'';
echo '<option '.$selected.' value="'.$row['Id'].'">'.$row['Etunimi'].' - '. $row['Sukunimi'].'</option>';
added a line above echo options ($selected = ($row['Id'] == $_REQUEST['select_employee'])?'selected="selected"':'';)
Added '.$selected.' in side options.
Your code becomes : Copy paste below code instead of yours
<form method="post">
<select name="select_employee" id="select_employee">
<?php $allemp=$this->AllEmployees; ?>
<option selected value="">Select an employee..</option>
<?php foreach($allemp as $row){
$selected = ($row['Id'] == $_REQUEST['select_employee'])?'selected="selected"':'';
echo '<option '.$selected.' value="'.$row['Id'].'">'.$row['Etunimi'].' - '. $row['Sukunimi'].'</option>';
} ?>
</select>
<input type="hidden" name="send" value="namesent">
<input type="submit" value="submit" id="button">
</form>
<br/>
<br/>

Refine Results with dropdown box

I would like to refine the results of mysql query using dropdown boxes... live site is here:
http://www.halfwayenterprises.com/search/tyrell.php
<form name="doublecombo" action="" method="POST">
<label for="status">Status:</label>
<label for="current">
<input class="radio_style" id="current" checked="checked" name="status" type="radio" value="current">
Current
</label>
<label for="obsolete">
<input class="radio_style" id="obsolete" name="status" type="radio" value="obsolete">
Obsolete
</label>
<label for="both">
<input class="radio_style" id="both" name="status" type="radio" value="both">
ALL
</label>
<br /><br />
<select name="category" size="1" onChange="redirect(this.options.selectedIndex)">
<option value="null">Category</option>
<option value="asset management">Asset Management</option>
<option value="budget">Budget/Finance</option>
<option value="central office">Central Office</option>
<option value="disposal">Disposal</option>
</select>
<select name="subcategory">
<option value="null">Sub-Category</option>
<option value="Portfolio">Portfolio</option>
<option value="Pricing">Pricing</option>
<option value="Valuation">Valuation</option>
<option value="Disposal">Disposal</option>
</select>
<input name="submitted" type="submit" value="GO">
<br />
Seach for: <input type="text" name="find" /> in
<Select NAME="field">
<Option id="title" VALUE="title">Title</option>
<Option id="poc" VALUE="poc">POC</option>
<Option id="purpose" VALUE="purpose">Purpose</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input name="submitted" type="submit" value="GO">
</form>
<select name="filter1">
<option value="az">Sort by A-Z</option>
<option value="date">Sort by Date</option>
</select>
<select name="filter2">
<option value="office">Sort by Office</option>
<option value="p">P</option>
<option value="pt">PT</option>
<option value="pf">PF</option>
</select>
<select name="filter3">
<option value="mandatory">Mandatory</option>
<option value="nonmandatory">Non-Mandatory</option>
<option value="combined">Combined</option>
</select>
</form>
</p>
<script>
<!--
/*
Double Combo Script Credit
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free JavaScripts here!
*/
var groups=document.doublecombo.category.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=new Option("Sub Category")
group[1][0]=new Option("Portfolio")
group[1][1]=new Option("Pricing")
group[1][2]=new Option("Valuation")
group[3][0]=new Option("Central Office")
group[4][0]=new Option("Disposal")
var temp=document.doublecombo.subcategory
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function go(){
location=temp.options[temp.selectedIndex].value
}
//-->
</script>
<?
mysql_connect("localhost", "name", "pasword") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
if(isset($_POST["submitted"])){
$status = $_POST['status'];
$category = $_POST['category'];
$subcategory = $_POST['subcategory'];
echo '<div class="status_div">';
if($status=='current')
{
echo "<h2>Results</h2><p>";
$res = mysql_query("SELECT * FROM material WHERE status='$status' AND category='$category' AND subcategory='$subcategory' ORDER BY `documentid` ASC");
while ($row = mysql_fetch_assoc($res)) {
echo '<div class="current">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
} if ($status=='obsolete')
{
echo "<h2>Results</h2><p>";
$res = mysql_query("SELECT * FROM material WHERE status='$status' AND category='$category' ORDER BY `documentid` ASC ");
while ($row = mysql_fetch_assoc($res)) {
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '<br>';
}
} if ($status=='both')
{
echo "<h2>Results</h2><p>";
$res = mysql_query("SELECT * FROM material WHERE status1='both' AND category='$category' ORDER BY `documentid` ASC");
while ($row = mysql_fetch_assoc($res)) {
echo '<div class="">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
}
echo '</div>';
}
$field = #$_POST['field'] ;
$find = #$_POST['find'] ;
$searching = #$_POST['searching'] ;
$status = $_POST['status'];
//This is only displayed if they have submitted the form
if ($searching =="yes")
{
echo "<h2></h2><p>";
//If they did not enter a search term we give them an error
if ($find == "")
{
echo "<a href='tyrell.htm'>Return</a>";
exit;
}
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
if($status=='current'){
$data = mysql_query("SELECT * FROM material WHERE status='$status' AND lower($field) LIKE'%$find%' LIMIT 0,30");
while ($row = mysql_fetch_assoc($data)) {
echo '<div class="current">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
}
if ($status=='obsolete'){
$data = mysql_query("SELECT * FROM material WHERE status='$status' AND lower($field) LIKE'%$find%' LIMIT 0,30");
while ($row = mysql_fetch_assoc($data)) {
echo '<div class="obsolete">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
} if ($status=='both'){
$data = mysql_query("SELECT * FROM material WHERE status1='both' AND lower($field) LIKE'%$find%' LIMIT 0,30");
while ($row = mysql_fetch_assoc($data)) {
echo '<div class="">';
echo $row ['documentid'].' - '.$row['category'].' - '.$row['title'].' - '.$row['status'];
echo '</div>';
echo '<br>';
}
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
<p align="center"><font face="arial" size="-2">This free script provided by</font><br>
<font face="arial, helvetica" size="-2"><a href="http://javascriptkit.com">JavaScript
Kit</a></font></p>'
</body>
</html>
I have can't think of how to use the drop downs without having a submit button
I think I know what you need...
Use jquery to submit form on you page.
Something like this...
$("submitted").click(function() {
var url = "file.php";
$.ajax({
type: "POST",
url: url,
data: $("doublecombo").serialize(), // serializes the form's elements.
success: function(data)
{
// populate box or div with your result
}
});
return false; // avoid reload.
});
//PHP part
if($_POST['someField']){
$result = //Do query and staff and return any type of resposne you will handle in ajax success
echo $result;
exit;
}
You can use JavaScript to manipulate the content of the dropdown list. All you need is to do is bind the click even on the radio button and when one of them gets clicked, use an Ajax call to retrieve the information from your SQL database and modify the content of your selectbox.
EDIT
Here's some code you can add to your page:
$('form[name=doublecombo] input').change(function() {
$('form[name=doublecombo]').submit();
});
Note that change might not work. If it doesn't, try using click instead.

Categories