I have this following codes.How do i send this form to php so in php i can access it like studentName course2 year3.Basically i have a table which looks like this studentName|course|year.I am looking for the right way to organize the data in order to insert it to my table.I have tried sending the form not as an array but i have to write 3 queries to insert 3 inputs.Is there any way to loop through the data and insert?
<form id="myform" method="POST">
<label>college:</label><input type="text" id="clg" name="clg"/><br/>
<label>Student:-</label><input type="text" name="name[]" id="name" />
<select name="taskOpen[]">
<option value="1">course1</option>
<option value="2">course2</option>
<option value="3">course3</option>
<option value="4">course4</option>
</select>
<select name="year[]">
<option value="1">year1</option>
<option value="2">year2</option>
<option value="3">year3</option>
<option value="4">year4</option>
</select>
<label>Student:-</label><input type="text" name="name[]" id="name" />
<select name="taskOpen[]">
<option value="1">course1</option>
<option value="2">course2</option>
<option value="3">course3</option>
<option value="4">course4</option>
</select>
<select name="year[]">
<option value="1">year1</option>
<option value="2">year2</option>
<option value="3">year3</option>
<option value="4">year4</option>
</select>
<input type="button" value="search" id="btn"/>
</form>
Here is what i have in php--
if(isset($_POST['name']) && isset($_POST['taskOpen'])
&& isset($_POST(['year'])){
$name=$_POST['name'],$course=$_POST['taskOpen'],$year=$_POST['year']
}
else {
echo "something";
}
foreach($name as $student){
$sql=$conn->prepare("INSERT INTO `student`(`studentName`) VALUES(:s_n)");
$sql->execute(array(":s_n"=>$student));
}
foreach($course as $courseN){
$sql=$conn->prepare("INSERT INTO `student`(`course`) VALUES(:co)");
$sql->execute(array(":co"=>$courseN));
}
foreach($year as $yearD){
$sql=$conn->prepare("INSERT INTO `student`(`year`) VALUES(:ya)");
$sql->execute(array(":ya"=>$yearD));
}
Here is what i think you are going for...
HTML
<!-- THE NAMES OF INPUT ELEMENTS WRAPPED IN A college_data-->
<form id="myform" method="POST">
<label>college:</label><input type="text" id="clg" name="college_data[clg]"/><br/>
<label>Student:-</label><input type="text" name="college_data[name]" id="name"/>
<select name="college_data[taskOpen1]">
<option value="1">course1</option>
<option value="2">course2</option>
<option value="3">course3</option>
<option value="4">course4</option>
</select>
<select name="college_data[year1]">
<option value="1">year1</option>
<option value="2">year2</option>
<option value="3">year3</option>
<option value="4">year4</option>
</select>
<label>Student:-</label><input type="text" name="name[]" id="name"/>
<select name="college_data[taskOpen2]">
<option value="1">course1</option>
<option value="2">course2</option>
<option value="3">course3</option>
<option value="4">course4</option>
</select>
<select name="college_data[year2]">
<option value="1">year1</option>
<option value="2">year2</option>
<option value="3">year3</option>
<option value="4">year4</option>
</select>
<input type="submit" value="search" id="btn"/>
</form>
PHP
<?php
$college = isset($_POST['college_data']['clg']) ? htmlspecialchars(trim($_POST['college_data']['clg'])) :null;
$studentName = isset($_POST['college_data']['name']) ? htmlspecialchars(trim($_POST['college_data']['name'])) :null;
$studentName2 = isset($_POST['college_data']['name2']) ? htmlspecialchars(trim($_POST['college_data']['name2'])) :null;
$taskOpen1 = isset($_POST['college_data']['taskOpen1']) ? htmlspecialchars(trim($_POST['college_data']['taskOpen1'])) :null;
$taskOpen2 = isset($_POST['college_data']['taskOpen2']) ? htmlspecialchars(trim($_POST['college_data']['taskOpen2'])) :null;
$year1 = isset($_POST['college_data']['year1']) ? htmlspecialchars(trim($_POST['college_data']['year1'])) :null;
$year2 = isset($_POST['college_data']['year2']) ? htmlspecialchars(trim($_POST['college_data']['year2'])) :null;
// TEST::: DELETE EVERYTHING BELOW THIS LINE ONCE YOU ARE DONE CONFIRMING THAT IT IS OK
// CLICK THE SUBMIT BUTTON TO SEE THE VALUES REFLECTED HERE AS SOON AS THE FORM GETS SUBMITTED...
var_dump($college);
var_dump($studentName);
var_dump($studentName2);
var_dump($taskOpen1);
var_dump($taskOpen2);
var_dump($year1);
var_dump($year2);
?>
VALIDATION
<?php
// FIRST CREATE AN ARRAY TO HOLD MESSAGES TO BE SHOWN TO THE USER
// SHOULD ANYTHING GO WRONG... & ALSO AN EMPTY ERROR MESSAGE STRING...
$arrErrorBag = array();
$strErrorMsg = "";
if(isset($_POST['submit'])) {
// LET'S ASSUME FOR THE MOMENT YOU HAVE SPECIAL CONSTRAINTS
// TO BE APPLIED TO EACH FIELD DURING YOUR VALIDATION PROCESS.
// WE WILL USE SIMPLE REGULAR EXPRESSIONS HERE FOR DEMONSTRATION
// BUILD VALIDATION REG-EXES FOR THE FIELD:: WE WANT ONLY A MINIMUM OF 10 CHARACTERS FOR STUDENT & COLLEGE
// AGAIN; YOU CAN GO WILD BUT WE ARE KEEPING IT SIMPLE
// PLUS, DOING IT LIKE THIS IS JUST SO THAT YOU GET THE DRIFT... ;-)
$rxColStudent = "#(.){10,}#si";
// FOR THE SELECTS, WE KNOW THAT THE VALUES ARE NUMBERS
// WHICH ARE BETWEEN 1 & 4; BUT WE TAKE IT TO "BETWEEN 1 & 9"
// AND WE INTEND USING ONE REGEX FOR ALL OF THEM SINCE THEY ARE SIMILAR.
$rxCourseYear = "#\d#";
// NOW WE HAVE THE REGEXES: THEN WHAT?
// VALIDATION BEGINS... ;-)
// TO MAKE IT EASIER ON OURSELVES, WE BUNDLE ALL THE STUDENT, STUDENT1 & COLLEGE FIELDS
// INTO AN ARRAY & LOOP THROUGH THE ARRAY, BUILDING THE ERRORS ON EACH ITERATION THROUGH THE LOOP.
// VALIDATE COLLEGE, STUDENT & STUDENT2...
$arrStringValFields = array(
"student" => array("Student Nr. 1", $studentName),
"student2" => array("Student Nr. 2 ", $studentName2),
"college" => array("College", $college),
);
// RUN THE LOOP & KEEP BUILDING THE ERRORS AS YOU VALIDATE THROUGH EACH ITERATION.
foreach ($arrStringValFields as $fieldName => $arrErrStringVal) {
if (!preg_match($rxColStudent, $arrErrStringVal[1])) {
$arrErrorBag[$fieldName] = $arrErrStringVal[0] . " is expected to have a minimum of 10 Characters. Please, check that you have not missed something.";
}
}
// TO MAKE IT AGAIN EASIER ON OURSELVES, WE BUNDLE ALL OTHER FIELDS THAT HAVE NUMERIC VALUES
// INTO AN ARRAY & LOOP THROUGH THE ARRAY, BUILDING THE ERRORS ON EACH ITERATION THROUGH THE LOOP.
$arrNumericFields = array(
"taskOpen1" => array("Open Task Nr. 1", $taskOpen1),
"taskOpen2" => array("Open Task Nr. 2 ", $taskOpen2),
"year1" => array("College Year Section 1", $year1),
"year2" => array("College Year Section 2", $year2),
);
// RUN THE LOOP & KEEP BUILDING THE ERRORS AS YOU VALIDATE THROUGH EACH ITERATION.
foreach ($arrNumericFields as $fieldName => $arrErrStringVal) {
if (!preg_match($rxCourseYear, $arrErrStringVal[1])) {
$arrErrorBag[$fieldName] = $arrErrStringVal[0] . " is expected to be a Single Digit & it should. Did you try to *NUKE OUR ASSES OFF*. Please, don't. We are your Brothers ;-)";
}
}
// MAMA MIA!!! SO MUCH FOR A SIMPLE 6-FIELD VALIDATION...
// HAPPILY ENOUGH; WE ARE THERE... ONLY; NOT JUST YET...
// CHECK THE ERROR BAG TO SEE IF IT CONTAINS ANYTHING.
// IF IT DOES; THEN WE HAVE TO FIND A WAY TO DISPLAY THIS TO THE END-USER.
if (!empty($arrErrorBag)) {
// TURN THE ERROR BAG ARRAY TO A STRING & ASSIGN IT BACK TO THE ERROR MESSAGE STRING FOR DISPLAY...
$strErrorMsg = "<span class='has-error'>" . implode("</span><br /><span class='has-error'>", $arrErrorBag);
}
else {
// WE HAVE REACHED THE CLIMAX OF OUR POLICE-WORK...
// SO WE EITHER STORE THE DATA TO THE DATABASE TABLE OR
// WE BAKE & CAKE IT FOR CHRISTMAS - YOUR CALL ;-)
}
}
?>
Now, that's OK. But how does the User get to know that there were Errors and how does s/he avoid typing-in the same information over again?
Our HTML File should have been built earlier to take that into consideration, but then again, EINTEIN WAS RIGHT!!! Human Stupidity is totally as Infinite as the Universe... but that's why we are here, right? To cut down the infinitude of our Stupidity and grow into real Humans;-) So we revise our HTML to take these into account.
HTML - REVISED: UNLEASH THE DRAGON!!!
<!-- WE ADD A SLOT FOR OUR ERROR MESSAGE: JUST BEFORE THE FORM. -->
<div class="error-slot"><?php echo $strErrorMsg; ?></div>
<form id="myform" method="POST">
<label>college:</label><input type="text" id="clg" name="college_data[clg]" value="<?php echo $college; ?>" /><br/>
<label>Student:-</label><input type="text" name="college_data[name]" value="<?php echo $studentName; ?>" id="name"/>
<select name="college_data[taskOpen1]">
<option value="1" <?php if($taskOpen1=="1"){echo "selected";} ?>>course1</option>
<option value="2" <?php if($taskOpen1=="2"){echo "selected";} ?>>course2</option>
<option value="3" <?php if($taskOpen1=="3"){echo "selected";} ?>>course3</option>
<option value="4" <?php if($taskOpen1=="4"){echo "selected";} ?>>course4</option>
</select>
<select name="college_data[year1]">
<option value="1" <?php if($year1=="1"){echo "selected";} ?>>year1</option>
<option value="2" <?php if($year1=="2"){echo "selected";} ?>>year2</option>
<option value="3" <?php if($year1=="3"){echo "selected";} ?>>year3</option>
<option value="4" <?php if($year1=="4"){echo "selected";} ?>>year4</option>
</select>
<label>Student:-</label><input type="text" name="college_data[name2]" value="<?php echo $studentName2; ?>" id="name"/>
<select name="college_data[taskOpen2]">
<option value="1" <?php if($taskOpen2=="1"){echo "selected";} ?>>course1</option>
<option value="2" <?php if($taskOpen2=="2"){echo "selected";} ?>>course2</option>
<option value="3" <?php if($taskOpen2=="3"){echo "selected";} ?>>course3</option>
<option value="4" <?php if($taskOpen2=="4"){echo "selected";} ?>>course4</option>
</select>
<select name="college_data[year2]">
<option value="1" <?php if($year2=="1"){echo "selected";} ?>>year1</option>
<option value="2" <?php if($year2=="2"){echo "selected";} ?>>year2</option>
<option value="3" <?php if($year2=="3"){echo "selected";} ?>>year3</option>
<option value="4" <?php if($year2=="4"){echo "selected";} ?>>year4</option>
</select>
<input type="submit" value="search" name="submit" id="btn"/>
</form>
From your table design in the database it looks like you want to insert a student, their course and the year they are taking it in. Unless you are going to validate the form so that the number of students matches the number of courses and numbers of years so you can easily loop and insert based on their indexes, i don't see how it can be easily done.
Example:
$_POST = Array(
'name' = Array ( 'Kelly', 'Tom', 'Jack' ),
'course' = Array ( 'Course1', 'Course2', 'Course3' ),
'year' = Array ( '2007', '2008', '2009' ),
);
for ( $i = 0; i < count($_POST['student_name']); i++ ) {
$sql = sprintf("INSERT INTO test ( student_name, course, year ) VALUES ( %s, %s, %d )",
$_POST['student_name'][$i], $_POST['course'][$i], $_POST['year'][$i]
);
$conn->query($sql);
}
Related
How can i pass Drop down values to sql database and also the check box for example if a user selects English and maths than the value inserted in to the database would be 1 or else the value would be 0
<form>
<p id="p1">Select Your Year</p>
<select id="year_sel">
<option value="blank"></option>
<option id="primary" value="primary">Primary</option>
<option value="1">Year one</option>
<option value="2">Year two</option>
<option value="3">Year Three</option>
</select>
<input type="checkbox" name="Math" value="Math">Math<br>
<input type="checkbox" name="English" value="English">English<br>
<input type="checkbox" name="HealthScience" value="HealthScience">Health Science<br>
<input class="sub_reg" type="submit" value="Register Subjects" />
</form>
this is how my database looks like
First, your <select id="year_sel"> needs a name attribute to post ->
<select id="year_sel" name="year_sel" >
Since you are using <form> the default is get, so you would get the selected value in $_GET
$year_sel = $_GET['year_sel'];
If you changed it to
<form method="post">
then you would get it in $_POST
$year_sel = $_POST['year_sel']
Second, checkboxes are only posted if checked, so you can use isset() to set a value using a ternary -
$math = isset($_GET['Math']) ? 1 : 0;
$english = isset($_GET['English']) ? 1 : 0;
...[rest of your checkboxes]...
swap $_GET/$_POST like the select
$math = isset($_POST['Math']) ? 1 : 0;
$english = isset($_POST['English']) ? 1 : 0;
<select id="year_sel" name="year_sel">
<option value="primary">Primary</option>
<option value="1">Year one</option>
<option value="2">Year two</option>
<option value="3">Year Three</option>
</select>
on your form action something.php file use this to get the select value
$language = $_POST["year_sel"]; // chose whetever your form method
establish the database connection please do refer some tutorials (if you don't know )
write the mysqli insert command like
$SQL = "INSERT INTO yourtable (language) VALUES ('$language')";
mysqli_real_escape_string($sql);
$result = mysqli_query($sql) or die (mysqli_error());
now you can insert this value in your mysql or any database table
this is not tested
<form>
<p id="p1">Select Your Year</p>
<select id="year_sel" name="year_sel">
<option value="blank"></option>
<option id="primary" value="primary">Primary</option>
<option value="1">Year one</option>
<option value="2">Year two</option>
<option value="3">Year Three</option>
</select>
<?php
$variable = $_POST["year_sel"];
?>
Should mention the HTML ELEMENT name to get the value.
I'm a newbie on PHP programming but I have to use it for a page in my blog that permit the users to search inside the blog using a radiobox and a selectbox. I've read some discussion about it but I can't find the error in my code.
This is my situation: I would permit a searching by brand or by model or by cc in my blog that talks about motorcycles, so I have a form with three radiobox that enables/disables the three selectboxes below. One for each category above-named. Clicking a button, the user will be redirected to the respective link /brand/ or /model/ or /cc/.
This is my HTML form:
<form name="admin" method="post" action="/search.php">
<input type="radio" name="rdo_brand" value="brand" id="r_brand" onclick="document.getElementById('r_model').checked=false;document.getElementById('r_cc').checked=false;document.getElementById('box_brand').disabled=false;document.getElementById('box_model').disabled=true;document.getElementById('box_cc').disabled=true;"> Search by brand
<input type="radio" name="rdo_model" value="model" id="r_model" onclick="document.getElementById('r_brand').checked=false;document.getElementById('r_cc').checked=false;document.getElementById('box_brand').disabled=true;document.getElementById('box_model').disabled=false;document.getElementById('box_cc').disabled=true;"> Search by model
<input type="radio" name="rdo_cc" value="cc" id="r_cc" onclick="document.getElementById('r_brand').checked=false;document.getElementById('r_model').checked=false;document.getElementById('box_brand').disabled=true;document.getElementById('box_model').disabled=true;document.getElementById('box_cc').disabled=false;"> Search by cc
Brand
<select name="brand" id="box_brand" />
<option value="-">-</option>
<option value="bmw">Bmw</option>
<option value="ducati">Ducati</option>
<option value="honda">Honda</option>
</select>
Model
<select name="model" id="box_model" />
<option value="-">-</option>
<option value="k1200gt">K1200GT</option>
<option value="monster">Monster</option>
<option value="silverwing>Silver Wing</option>
</select>
CC
<select name="cc" id="box_cc" />
<option value="-">-</option>
<option value="600">600</option>
<option value="900">900</option>
<option value="1200">1200</option>
</select>
<input type="submit" value="Search" id="btn_search" />
>/form>
And this is my search.php:
// Data recovery process
// I know it's not the better way but is the most simply for a newbie like me!
if (empty($_POST['brand']))
{
$brand = 'nothing';
}
else
{
$brand = $_POST['brand'];
}
if (empty($_POST['model']))
{
$model = 'nothing';
}
else
{
$model = $_POST['model'];
}
if (empty($_POST['cc']))
{
$cc = 'nothing';
}
else
{
$cc = $_POST['cc'];
}
// Replacing spaces in acquired variables
$brand = str_replace(" ", "-", $brand);
$model = str_replace(" ", "-", $model);
$cc = str_replace(" ", "-", $cc);
// Control process
if ($brand <> 'nothing')
{
header("location: mysite.com/categories/brands/$brand/");
exit;
}
else
{
if ($model <> 'nothing')
{
header("location: mysite.com/categories/models/$model/");
exit;
}
else
{
header("location: mysite.com/categories/cc/$cc/");
exit;
}
}
I think the code is correct but, obviously, it's not, because doesn't work completely. If I check the rdo_brand and I select one of the option inside the brand (bmw for example), the redirect works fine to mysite.com/categories/brands/bmw/... but if I check the rdo_model and I select one of the option inside the model, the redirect wrongly take me to mysite.com/categories/cc/nothing/
I can't understand! Why is this happening?
Try fixing the typos in the html code (see bellow)
<form name="admin" method="post" action="/search.php">
<input type="radio" name="rdo_brand" value="brand" id="r_brand" onclick="document.getElementById('r_model').checked=false;document.getElementById('r_cc').checked=false;document.getElementById('box_brand').disabled=false;document.getElementById('box_model').disabled=true;document.getElementById('box_cc').disabled=true;"> Search by brand
<input type="radio" name="rdo_model" value="model" id="r_model" onclick="document.getElementById('r_brand').checked=false;document.getElementById('r_cc').checked=false;document.getElementById('box_brand').disabled=true;document.getElementById('box_model').disabled=false;document.getElementById('box_cc').disabled=true;"> Search by model
<input type="radio" name="rdo_cc" value="cc" id="r_cc" onclick="document.getElementById('r_brand').checked=false;document.getElementById('r_model').checked=false;document.getElementById('box_brand').disabled=true;document.getElementById('box_model').disabled=true;document.getElementById('box_cc').disabled=false;"> Search by cc
Brand
<select name="brand" id="box_brand" />
<option value="-">-</option>
<option value="bmw">Bmw</option>
<option value="ducati">Ducati</option>
<option value="honda">Honda</option>
</select>
Model
<select name="model" id="box_model" />
<option value="-">-</option>
<option value="k1200gt">K1200GT</option>
<option value="monster">Monster</option>
<option value="silverwing">Silver Wing</option>
</select>
CC
<select name="cc" id="box_cc" />
<option value="-">-</option>
<option value="600">600</option>
<option value="900">900</option>
<option value="1200">1200</option>
</select>
<input type="submit" value="Search" id="btn_search" />
</form>
I am using Magento and using Custom Options. I have 5 custom options that allow the user to choose the condition of the item. I want some text below to show what the condition means when they select it.
Im sorry for the confusion. I want this to update live on the screen when the appropriate option is selected.
Here is my current code but it isn't displaying the text.
<select name="options[1][]" id="select_1" class="multiselect required-entry product-custom-option" title="" onchange="opConfig.reloadPrice()">
<option value="1" price="0" >Perfect </option>
<option value="2" price="-35" >Excellent </option>
<option value="3" price="-105" >Good </option>
<option value="4" price="-140" >Poor </option>
<option value="5" price="-252" >Broken </option></select>
<?php if( $_POST['select_1']=='1' ){
echo "Perfect Condition Text";
}elseif( $_POST['select_1']=='2' ){
echo "Excellent Condition Text";
}elseif( $_POST['select_1']=='3' ){
echo "Good Condition Text";
}elseif( $_POST['select_1']=='4' ){
echo "Poor Condition Text";
}elseif( $_POST['select_1']=='5' ){
echo "Broken Condition Text";
} ?>
Changing the <select> name to select_1 will solve your problem:
<select name="select_1" id="select_1" class="multiselect required-entry product-custom-option" title="" onchange="opConfig.reloadPrice()">
If you can't change the names for some reason, change $_POST['select_1'] to $_POST['options'][1][0]
If you want to display the value of the <select> without refreshing the page then you could use javascript or jquery. Here is a sample of Javascript:
<script language="javascript">
function displayCondition() {
condition = new Array("", "Perfect", "Excellent", "Good", "Poor", "Broken");
var getsel = document.getElementById('select_1').value;
document.getElementById("divId").innerHTML = condition[getsel];
}
</script>
</head>
<body>
<form name="formName">
<select name="options[1][]" id="select_1" class="multiselect required-entry product-custom-option" title="" onchange="displayCondition()">
<option value="0">Select Condition</option>
<option value="1" price="0" >Perfect</option>
<option value="2" price="-35" >Excellent</option>
<option value="3" price="-105" >Good</option>
<option value="4" price="-140" >Poor</option>
<option value="5" price="-252" >Broken</option>
</select>
<div id="divId" name="divName" ></div>
</form>
</body>
</html>
The array will not be available in PHP $_POST by select_1 index but PHP $_POST is going to have an options array $_POST['options']
The post array name is based on the name of the form element, not the id of the form element. Change the name property of your select element to "select_1" and you will get what you are looking for.
I am creating a meat packaging search form, users can search for different packages using multiple forms and dropdown boxes. I have a had a lot of problems but most of it is sorted now, I only need to create an "Any" search for the dropdown boxes and the problem of empty textboxes displaying all results.
Currently when a user sends a search, they may have entered in some other text boxes, but when one of the forms is left empty that automatically displays all of the results. I want it so when a search is sent and a box is empty, the code ignores that form and just checks the ones that have info inside of them.
here is my test code (not my current final form code):
<body>
<?php
$con = mysql_connect("localhost", "root", "");
mysql_select_db("delyn_db", $con);
if (!$con)
{
die("Could not connect: " . mysql_error());
}
$descrip = mysql_real_escape_string($_POST['descrip']);
$sql = "SELECT * FROM delyn WHERE description LIKE '%" . $descrip . "%'";
$r_query = mysql_query($sql);
if ($descrip === "")
{
echo 'Null value';
}
while ($row = mysql_fetch_array($r_query))
{
echo '<br /> Description: ' . $row['description'];
}
?>
</body>
Anyone have any ideas on how to stop this?
EDIT: Sorry here is my HTML with the search boxes. The above php is just where the values are sent.
<body>
<form action="form5null.php" method="post">
<label for="description">Description:</label> <input type="text" name="descrip">
<br>
<label for="trayheight">Trayheight:</label> <input type="text" name="height">
<br>
<label for="traywidth">Traywidth:</label> <input type="text" name="width">
<br>
<label for="traydepth">Traydepth:</label> <input type="text" name="depth">
<br>
<label for="trayrange">Trayrange:</label> <select name="trayrange">
<option value="BBQ">
BBQ
</option>
<option value="Dessert">
Dessert
</option>
<option value="Display">
Display
</option>
<option value="Meat">
Meat
</option>
<option value="Microwave">
Microwave
</option>
<option value="Party">
Party
</option>
<option value="Salad/Wet Pasta">
Salad/Wet Pasta
</option>
<option value="Snacks">
Snacks
</option>
<option value="Standard">
Standard
</option>
</select> <label for="traytype">Traytype:</label> <select name="traytype">
<option value="Open">
Open
</option>
<option value="Cavitised">
Cavitised
</option>
<option value="Lid">
Lid
</option>
<option value="Tray">
Tray
</option>
<option value="Coallition">
Coallition
</option>
<option value="Bowl">
Bowl
</option>
<option value="Hinge pack">
Open
</option>
<option value="Pot">
Pot
</option>
<option value="Base & Lid">
Base and Lid
</option>
<option value="Rectangular">
Rectangular
</option>
<option value="Specalist">
Specialist
</option>
</select>
<br>
<label for="trayshape">Trayshape:</label> <select name="trayshape">
<option value="Rectangular">
Rectangular
</option>
<option value="Oval">
Oval
</option>
<option value="Square">
Square
</option>
<option value="Insert">
Insert
</option>
<option value="Round">
Round
</option>
<option value="Open">
Open
</option>
</select>
<br />
<input type="submit" value="Submit">
</form>
</body>
Add the following as the first option to all your dropdowns:
<option value="*">All</option>
Then use the SQL I provided in your duplicate question here:
Make SQL ignore a specific search value if clicked in a dropdown?
Dirk Nachbar gave a good answer as well.
Have you tried limiting your SQL queries by just checking if the values are blank/null (whichever is appropriate for PHP) and just not running the query if nothing is filled in?
e.g. (pseudocode)
if(box1.HasText || box2.HasText || box3.HasText)
{
RunTheSqlForForm1();
}
This question already has answers here:
Using $_POST to get select option value from HTML
(8 answers)
Closed 6 years ago.
I am trying to get the option selected using PHP, but I ran out of ideas!
Below is the code I have tried until now:
<select>
<option value="1">Yes</options>
<option value="2">No</options>
<option value="3">Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
So, what do I have to do?
Programmers are lazy...er....efficient....I'd do it like so:
<select><?php
$the_key = 1; // or whatever you want
foreach(array(
1 => 'Yes',
2 => 'No',
3 => 'Fine',
) as $key => $val){
?><option value="<?php echo $key; ?>"<?php
if($key==$the_key)echo ' selected="selected"';
?>><?php echo $val; ?></option><?php
}
?></select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
<select>
<option value="1" <?php if ($myVar==1) echo 'selected="selected"';?>>Yes</options>
<option value="2" <?php if ($myVar==2) echo 'selected="selected"';?>>No</options>
<option value="3" <?php if ($myVar==3) echo 'selected="selected"';?>>Fine</options>
</select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
This is a very simple and straightforward way, if I understand your question correctly.
you can use this..
<select name="select_name">
<option value="1"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='1')?' selected="selected"':'');?>>Yes</option>
<option value="2"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='2')?' selected="selected"':'');?>>No</option>
<option value="3"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='3')?' selected="selected"':'');?>>Fine</option>
</select>
First of all give a name to your select. Then do:
<select name="my_select">
<option value="1" <?= ($_POST['my_select'] == "1")? "selected":"";?>>Yes</options>
<option value="2" <?= ($_POST['my_select'] == "2")? "selected":"";?>>No</options>
<option value="3" <?= ($_POST['my_select'] == "3")? "selected":"";?>>Fine</options>
</select>
What that does is check if what was selected is the same for each and when its found echo "selected".
I suppose that you are using an array to create your select form input.
In that case, use an array:
<?php
$selected = array( $_REQUEST['yesnofine'] => 'selected="selected"' );
$fields = array(1 => 'Yes', 2 => 'No', 3 => 'Fine');
?>
<select name=‘yesnofine'>
<?php foreach ($fields as $k => $v): ?>
<option value="<?php echo $k;?>" <?php #print($selected[$k]);?>><?php echo $v;?></options>
<?php endforeach; ?>
</select>
If not, you may just unroll the above loop, and still use an array.
<option value="1" <?php #print($selected[$k]);?>>Yes</options>
<option value="2" <?php #print($selected[$k]);?>>No</options>
<option value="3" <?php #print($selected[$k]);?>>Fine</options>
Notes that I don't know:
how you are naming your input, so I made up a name for it.
which way you are handling your form input on server side, I used $_REQUEST,
You will have to adapt the code to match requirements of the framework you are using, if any.
Also, it is customary in many frameworks to use the alternative syntax in view dedicated scripts.
I use inline if's
($_POST['category'] == $data['id'] ? 'selected="selected"' : false)
I have 2 php files and i made this, and it works.
(this is an example) the first code is from the one file and the second code from two file.
<form action="two.php" method="post">
<input type="submit" class="button" value="submit" name="one"/>
<select name="numbers">
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
</select>
</form>
if(isset ($_POST['one']))
{
if($_POST['numbers']=='1')
{
$a='1' ;
}
else if($_POST['numbers']=='2')
{
$a='2' ;
{
else if ($_POST['numbers']=='3')
{
$a='3' ;
}
}
This answer is not relevant for particular recepient, but maybe useful for others.
I had similiar issue with 'selecting' right 'option' by value returned from database.
I solved it by adding additional tag with applied display:none.
<?php
$status = "NOT_ON_LIST";
$text = "<html>
<head>
</head>
<body>
<select id=\"statuses\">
<option value=\"status\" selected=\"selected\" style=\"display:none\">$status</option>
<option value=\"status\">OK</option>
<option value=\"status\">DOWN</option>
<option value=\"status\">UNKNOWN</option>
</select>
</body>
</html>";
print $text;
?>
This is the solution that I've came up with:
<form name = "form1" id = "form1" action = "#" method = "post">
<select name = "DropDownList1" id = "DropDownList1">
<?php
$arr = array('Yes', 'No', 'Fine' ); // create array so looping is easier
for( $i = 1; $i <= 3; $i++ ) // loop starts at first value and ends at last value
{
$selected = ''; // keep selected at nothing
if( isset( $_POST['go'] ) ) // check if form was submitted
{
if( $_POST['DropDownList1'] == $i ) // if the value of the dropdownlist is equal to the looped variable
{
$selected = 'selected = "selected"'; // if is equal, set selected = "selected"
}
}
// note: if value is not equal, selected stays defaulted to nothing as explained earlier
echo '<option value = "' . $i . '"' . $selected . '>' . $arr[$i] . '</option>'; // echo the option element to the page using the $selected variable
}
?>
</select> <!-- finish the form in html -->
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
</form>
The code I have works as long as the values are integers in some numeric order ( ascending or descending ). What it does is starts the dropdownlist in html, and adds each option element in php code. It will not work if you have random values though, i.e: 1, 4, 2, 7, 6. Each value must be unique.