keep php result as content in div - php

EDIT!!! : LINK = http://i299291.iris.fhict.nl/PHP31/DV3/DV3.php
My problem:
I've made two dropdown boxes with several options. The php code is working and the query gets the right result from the database. But now i want to compare two options.
This is what i've got so far, the problem now is the entire page refreshes when i enter the second value from the other dropdown box.
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form id = "leftDropdown" action= "" method="post">
<select name="objectLinks">
<option value="school">School</option>
<option value="klas">Klas</option>
<option value="geslacht">Geslacht</option>
<option value="lengte">Lengte (CM)</option>
<option value="kg">Gewicht (KG)</option>
<option value="opleiding">Opleiding Ouders</option>
<option value="leeftijdJaar">Leeftijd</option>
<option value="interventie">Deelname interventie?</option>
<option value="pestenVoor">Pestincidenten voor interventie</option>
<option value="pestenNa">Pestincidenten na interventie</option>
<option value="bmi">BMI waarde</option>
<option value="overgewicht">Overgewicht</option>
<option value="allochtonenPerc">Percentage Allochtonen</option>
</select>
<input type="submit" name="sendLinks" value="Go!">
</form>
<form id = "rightDropdown" action= "" method="post">
<select name="objectRechts">
<option value="school">School</option>
<option value="klas">Klas</option>
<option value="geslacht">Geslacht</option>
<option value="lengte">Lengte (CM)</option>
<option value="kg">Gewicht (KG)</option>
<option value="opleiding">Opleiding Ouders</option>
<option value="leeftijdJaar">Leeftijd</option>
<option value="interventie">Deelname interventie?</option>
<option value="pestenVoor">Pestincidenten voor interventie</option>
<option value="pestenNa">Pestincidenten na interventie</option>
<option value="bmi">BMI waarde</option>
<option value="overgewicht">Overgewicht</option>
<option value="allochtonenPerc">Percentage Allochtonen</option>
</select>
<input type="submit" name="sendRechts" value="Vergelijk!">
</form>
<div id = "leftDiv">
<?php
include_once 'dv3ToDB.php'; // connect to database *local or at school's server*
session_start();
if(isset($_POST['sendLinks'])){
$selectedValLinks = $_POST['objectLinks'];
// echo "Jij selecteerde: ".$selectedVal;
echo "<script>console.log('$selectedValLinks');</script>";
// $_SESSION["valLinks"] = $selectedValLinks;
// echo $_SESSION["valLinks"];
$query = "SELECT ($selectedValLinks) FROM pesten ORDER BY ($selectedValLinks) * 1";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Gevonden data in ".$selectedValLinks.": " . $row["$selectedValLinks"] . "<br>" ;
}
}else{
echo "0 results";
}
}
?>
</div>
<div id = "rightDiv">
<?php
if(isset($_POST['sendRechts'])){
$selectedValRechts = $_POST['objectRechts'];
// echo "Jij selecteerde: ".$selectedVal;
echo "<script>console.log('$selectedValRechts');</script>";
// $_SESSION["valRechts"] = $selectedValRechts;
// echo $_SESSION["valRechts"];
$conn = mysqli_connect($host,$username,$password,$database)
or die("verbinding mislukt:".mysqli_connect_error());
$query = "SELECT ($selectedValRechts) FROM pesten ORDER BY ($selectedValRechts) * 1";
$result = $conn->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Gevonden data in ".$selectedValRechts.": " . $row["$selectedValRechts"] . "<br>" ;
}
}else{
echo "0 results";
}
}
?>
</div>
</body>
</html>
i'm running it local now, let me know if you need me to build a database online to help me out.
How can i code it so the PHP output stays in de left DIV and/or the right DIV?
Thank you so much guys and girls! :)

If you need to use only PHP, without any JavaScript (which could allow you to display the result from the database after selecting each option without reloading the page), I'd suggest that, after submitting one form, you add it's result as a hidden input for the other form, so you could read this variable after submitting the 2nd form.
Like this:
<? // Your code for getting the result of the 1st form above returns a variable $res1
// Now insert this into the 2nd form:?>
<input type="hidden" name="stored2" value="<?echo $res1;?>"/>
This way, you can read the variable $_POST["stored2"] after submitting the 2nd form to get what the 1st form returned before.
Do the same for the 1st form to store the results of the 2nd form if it was filled first.
This way, you can compare the results of submitting 2 forms while using only PHP.
EDIT:
You'll need to place all the database requests before the forms to use this method, and just echo the result in the div later.

You want to make a new <iFrame> and then set that <iFrame>'s id as the target for your form.
e.g.:
<form ... target="newframe">
...
</form>
<iFrame id="newframe"></iFrame>

As Lal mentioned you don't need two forms, just one will work.
You need some code that updates the option to selected, if you don't want it to "stick" on page refresh.
Further reading here;
http://www.w3schools.com/tags/att_option_selected.asp
and here
html select option SELECTED
Even try Jquery;
http://forum.jquery.com/topic/how-to-dynamically-select-option-in-dropdown-menu

Related

Posting the value of a drop down menu to a PHP page via a HTML form

I'm creating a form in HTML which sends the question a user is asking, and the topic which the question should appear under to a PHP page. The topic names are pulled from a MySQL database using PHP.
I want to post the value of the drop down menu (the topic that the user has chosen) along with a HTML form to a PHP page. Here is my form code:
<form action="add_question.php" method="post">
Question:<input name="question_text" type="question"><br>
<select name="topic_name">
<option>Topic</option>
<?php
// Get each topic name from the database
include "connect_database.php";
$topicQuery = "SELECT topic_name FROM topics
ORDER BY topic_name";
$result = $conn->query($topicQuery);
if ($result->num_rows > 0)
{
while ($row = $result->fetch_assoc())
{
// Make topic an option in drop down box
echo '<option>' . $row["topic_name"] . '</option>';
}
}
// Close connection
mysqli_close($conn);
?>
</select><br>
<button type="submit">Submit</button>
</form>
When this is posted to add_question.php, $_POST['topic_name'] has no value. I think there's a problem with my form, although I can't see what. Any help would be great.
Thanks!
You have to assign a value to your options like :
echo '<option value='.$row["topic_id"].'>' . $row["topic_name"] . '</option>';
Note: topic_id an exmaple of a value you may use any other value
You need to add value attribute to all your options
<option value="some value">some value</option>
<form action="add_question.php" method="post">
Question:<input name="question_text" type="question"><br>
<select name="topic_name">
<option>Topic</option>
<?php
// Get each topic name from the database
include "connect_database.php";
$topicQuery = "SELECT topic_name FROM topics
ORDER BY topic_name";
$result = $conn->query($topicQuery);
if ($result->num_rows > 0)
{
while ($row = $result->fetch_assoc())
{ ?>
<option value="<?=$row["topic_name"]?>"><?=$row["topic_name"]?></option>
<?php
}
}
// Close connection
mysqli_close($conn);
?>
</select><br>
<button type="submit">Submit</button>
</form>
Try the following:
<form action="add_question.php" method="POST">
Question: <input name="question_text" type="question"><br/>
<select name="topic_name">
<option>Topic 1</option>
<option>Topic 2</option>
<option>Topic 3</option>
</select>
<input type="submit" value="submit">
</form>
Note that you don't need a value as mentioned above and you are going to fill your options using your database of course. And notice the input type="submit".
Then on the page add_question.php do the following:
echo $_POST["question_text"];
echo "<br/>";
echo $_POST["topic_name"];
That prints out the correct items when I use it.

Retrieve post value from php of dropdown select upon page

I have a drop down select inside of a form on my page nice.php which is submitted using a button
<form action="nice.php" method="post">
<select name="CarList">
<option value="0"> - Select Car - </option>
<option value="AM">Aston Martin</option>
<option value="KG">Koenigsegg</option>
<option value="MB">Mercedes Benz</option>
</select>
<input type="submit">
</form>
After making a selection is it possible to submit the form, reload the same page however with the value from the dropdown into a php variable $SelectedCar?
if(!empty($_POST['CarList'])){
$SelectedCar = $_POST['CarList'];
echo $SelectedCar;
}else{
echo '<p>No Selection has been made and submitted yet</p>';
}
Add the code to the top of your php page and remove the form tags. This should do a post back to the same page. (Remember to check if any variables are set in $_POST )
I haven't tested this suggestion yet but it should work
** Edit.
So Your HTML should look something like this:
<?php
if(isset($_POST['CarList']) && !empty(isset($_POST['CarList'])){
$CarListValue = $_POST['CarList'];
if($CarListValue != 0){ // a selection has been made using car list
$SelectedCar = $CarListValue
echo $SelectedCar // should print either 'AM', 'KG', or 'MB'
}
else{
echo '<p>No Selection has been made and submitted yet</p>';
}
}
?>
<html>
<head>
<title>Nice.php</title>
</head>
<body>
<select name="CarList">
<option value="0"> - Select Car - </option>
<option value="AM">Aston Martin</option>
<option value="KG">Koenigsegg</option>
<option value="MB">Mercedes Benz</option>
</select>
<submit>Submit Form</submit>
</body>
</html>
You could then take your validation to another level and change the php code like this as well:
<?php
$ValidCars = array('AM','KG','MB');
if(isset($_POST['CarList']) && !empty(isset($_POST['CarList'])){
$CarListValue = $_POST['CarList'];
if(in_array($CarListValue,strtoupper($ValidCars),false) !== true){
die('<b>The car selection you made is invalid</b>');
}
if($CarListValue != 0){ // a selection has been made using car list
$SelectedCar = $CarListValue
echo $SelectedCar // should print either 'AM', 'KG', or 'MB'
}
else{
echo '<p>No Selection has been made and submitted yet</p>';
}
}
?>
I just want to say again that this code is untested but the in theory the code should work without any error

get value from combo box to php

this is my combo box page coding:
<?php
echo "<form method=post align=center>
<div id=myDiv>
<select name=userselect>
<option value=empty></option>
<option value=Confirm> Confirm </option>
<option value=Processing> Processing </option>
<option value=Pending> Pending </option>
<option value=Cancelled> Cancelled </option>
</select>
<button type=button name=combobox value=combobox onclick=loadXMLDoc()>Update</button>
</div>
</form>";
?>
this is my php code (another page):
<?php
if (isset($_POST['combobox']))
{
$userselect = $_POST['userselect'];
echo $userselect;
}
?>
if user select one value in combo box that value should store in db and then display what they are selected. for example if user select CONFIRM option that value stored in db after that it display CONFIRM instead of that combo box form and button. Here i can stored the combo box values in db successfully. thats not a problem and then here i used ajax method to show the msg instead of button place. Now, i want what user select it should display the same value. check these above coding and reply me ur suggestions...
Replace Your code with this:
<?php
//Connect To your Database File..
//After Connecting To Databse
$combo = mysqli_real_escape_string('yourconnectionlink', $_POST['userselect'])
echo "<form method='post' action='youractionfile.php' align='center'>
<div id='myDiv'>
<select name='userselect'>
<option value='empty'></option>
<option value='Confirm'> Confirm </option>
<option value='Processing'> Processing </option>
<option value='Pending'> Pending </option>
<option value='Cancelled'> Cancelled </option>
</select>
<input type='button' name='combobox' value='combobox'>Update</button>
</div>
</form>";
//Insert Data into Database File
if($_POST['userselect'])) {
if(isset($_POST['userselect'])) {
$query = "INSERT INTO tablename (your field names) VALUES ('".$combo."')";
$res = mysqli_query('yourconnectionlink', $query);
echo '1 row inserted';
}
}
?>
finally i got it what i want. without using ajax method i can store the data to db and then combobox, button hide permanently if once we updated the status. this is my final coding...
if ( $a_row['status'] != 'empty' ) {
echo "\t<td>" . $a_row[$status] . "</td>\n";
}
else {
echo "\t<td><form action=statusdb.php method=post>
<select name=update>
<option value=empty></option>
<option value=Confirm>Confirm</option>
<option value=Processing>Processing</option>
<option value=Pending>Pending</option>
<option value=Cancelled>Cancelled</option></select>
<input name=id type=hidden value='".$a_row['slno']."';>
<input type=submit value=Update>
</form>
</td>\n";
}
statusdb coding:
if (isset($_POST['id']))
{
$id = mysql_real_escape_string($_POST['id']);
$update= mysql_real_escape_string($_POST['update']);
$sql = mysql_query("UPDATE guest_details SET status = '$update' WHERE slno = '$id'");
if(!$sql)
{
die("Error" .mysql_error());
}
}
i posted another question (php combobox & button should hide once updated into mysql db and show success message instead of combobox & button place.). i got help from that answer... so, only i posted the correct answer here..

Select from drop-down menu and reload page

I've got a table that populates data from a MYSQL database and populates a drop-down menu from the same database. I have the drop down menu and table just fine, I would like to be able to choose which data I show in the table however.
<select name = 'peer-id' method='post' style = 'position: relative'>
<?php
while ($content = mysql_fetch_array($peer)) {
echo "<option value='" . $content['Peer'] . "'>" . $content['Peer'] . "</option>";
}
$results = mysql_query("SELECT Destination FROM rate ");
?>
</select>
That's what I have for the select box. How can I get the choice from that and save that as a variable and refresh the table data?
I need to clarify that this will change that current data
#Data#Data#Data
#Data#Data#Data
#Data#Data#Data
Then choose drop down choice and I want it to show new data
#Data2#Data2#Data2
#Data2#Data2#Data2
#Data2#Data2#Data2
So it's going to need to load a new page or refresh some how because it's changing via PHP and not javascript.
I think form may be better, for example
<form id="myform" method="post">
<select name = 'peer-id' style = 'position: relative' onchange="change()">
<option value="1">12</option>
<option value="2">15</option>
<option value="3">16</option>
<option value="4">18</option>
</select>
</form>
<script>
function change(){
document.getElementById("myform").submit();
}
</script>
In the above code, whenever you change the value of select, it will post to the backend, then according to the posted value, you can do want you want, to get the peer-id in php, you can use the following code
$peer-id = $_POST['peer-id'];
Hope helps!
apply this code in select tag hope this works
<select onchange="location = this.options[this.selectedIndex].value;" style="text-decoration:none;">
<option value="customers.php"></font></option>
</select>
insted of the static options, you can do it like this :) here you get all the options from the database. Just replace it with the static options
$peer = mysql_query("SELECT Peer FROM rate Group By Peer Where peer = 'variable'");
$result_peer = mysql_query($peer);
if($result_peer){
while($row_peer = mysql_fetch_array($result_peer)){
echo'<option value='.$row_peer['Peer'].'>'.$row_peer['Peer'].'</option>';
}
I agree in using form, and with this you can echo back onto the page with a submit button (code tested):
<form id="myForm" method="POST">
<select name="select" onchange="<?php echo $_SERVER['PHP_SELF'];?>">
<option value="N">No</option>
<option value="Y">Yes</option>
</select>
<input type="submit" name="formSubmit" value="Submit" >
</form>
<?php
if(isset($_POST['formSubmit']) ){
$var = $_POST['select'];
$query = "SELECT * FROM table_name WHERE DesiredField='$var'";
$result = mysql_query($query)
or die(mysql_error());
while($row = mysql_fetch_array($result)){
$var2 = $row['FieldName'];
echo "First field: " . $var2 . "<br>";
// and so on for what you want to echo out
}
}
?>

How to Keep the selected value of the select box after Form POST or GET

Im trying to implement the search feature in my website.
when the search keyword is entered in the textbox, and the category combo is selected, the form will be Posted and the result will be shown on the same page.
what i want is to keep the selected category of the combo by default in the form after posted
For eg., If i select the category 'Automobiles' in the combo and click search, after form submit, the combo should show the automobiles as default selected option. Please help me. Any help will be appreciated
I assume you get categories from database.
you should try:
<?php
$categories = $rows; //array from database
foreach($rows as $row){
if($row['name'] == $_POST['category']){
$isSelected = ' selected="selected"'; // if the option submited in form is as same as this row we add the selected tag
} else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$row['id']."'".$isSelected.">".$row['name']."</option>";
}
?>
Assuming that by "combo" you mean "A regular select element rendering as a drop down menu or list box" and not "A combobox that is a combination of a drop down menu and free text input":
When outputting the <option> elements, check the value against the submitted data in $_POST / $_GET and output selected (in HTML) or selected="selected" (in XHTML) as an attribute of the option element.
Here is the JQuery way I am using.
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
$("#name").val("<?php echo $_POST['name'];?>");
</script>
But this is only if you have jquery included in your webpage.
Regards
<?php
$example = $_POST["friend"];
?>
<form method="POST">
<select name="friend">
<option value="tom" <?php if (isset($example) && $example=="tom") echo ' selected';?>>Thomas Finnegan</option>
<option value="anna" <?php if (isset($example) && $example=="anna") echo ' selected';?>>Anna Karenina</option>
</select>
<br><br>
<input type="submit">
</form>
This solved my problem.
This Solved my Problem. Thanks for all those answered
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>
$countries_uid = $_POST['countries_uid'];
while($row = mysql_fetch_array($result)){
$uid = $row['uid'];
$country = $row['country_name'];
$isSelected = null;
if(!empty($countries_uid)){
foreach($countries_uid as $country_uid){//cycle through country_uid
if($row['uid'] == $country_uid){
$isSelected = 'selected="selected"'; // if the option submited in form is as same as this row we add the selected
}
}
}else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$uid."'".$isSelected.">".$country."</option>";
}
this is my solutions of multiple select dropdown box after modifying Mihai Iorga codes
After trying al this "solves" nothing work. Did some research on w3school before and remember there was explanation of keeping values about radio. But it also works for Select option. See here an example. Just try it out and play with it.
<?php
$example = $_POST["example"];
?>
<form method="post">
<select name="example">
<option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
<option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
<option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
Easy solution:
If select box values fetched from DB then to keep selected value after form submit OR form POST
<select name="country" id="country">
<?php $countries = $wpdb->get_results( 'SELECT * FROM countries' ); ?>
<option value="">
<?php if(isset($_POST['country'])){echo htmlentities($_POST['country']); } else { echo "Select Country *"; }?>
</option>
<?php foreach($countries as $country){ ?>
<option <?php echo ($_POST['country'] == $country->country_name ? 'selected="selected"':''); ?> value="<?php echo $country->country_name; ?>"><?php echo $country->country_name; ?>
</option>
<?php } ?>
</select>

Categories