Select from drop-down menu and reload page - php

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
}
}
?>

Related

Displaying default value through select tag

I am having trouble passing & displaying default value for select tag. So, I have tried different variants of select and option tag but I am not able to get this right.
I want to fetch different options in form of a drop down menu. I want to display a default value in it. ($categorytemp[$i] in code). On displaying the form
A user can update this choice; or
A user can select the same choice again; or
A user can not change it at all.
Expected result for the above activity should be update, update, default value for $category
Below is the snapshot of my code
<select name="category" value="<?php echo $categorytemp[$i] ?>">
<?php
$sql = "SELECT * FROM education_details";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result))
{
$education_category = $row["id"];
$education_name= $row["name"];
?>
<option value='<?php echo $education_category?>'><?php echo $education_name;?></option>
<?php
}
?>
</select>
I tried using the option tag with selected attribute but that is making things more complicated. For example, if I use
<select name="category" value="<?php echo $categorytemp[$i] ?>">
<option selected="selected"><?php echo $categorytemp[$i]; ?> </option>
<?php
$sql = "SELECT * FROM education_details";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result))
{
$education_category = $row["id"];
$education_name= $row["name"];
?>
<option value='<?php echo $education_category?>'><?php echo $education_name;?></option>
<?php
}
?>
</select>
It displays the form as desired but on making no selection, it passes null value in the category. I have gone through questions of similar type asked earlier, but they do not answer my query to my satisfaction
You do it with a "selected" attribute of a given <option> and not in the <select> tag with the value attribute.
Check these two:
http://www.w3schools.com/tags/tag_select.asp
http://www.w3schools.com/tags/tag_option.asp
Have you consider using Javascript on the form submit to achieve it?
Another option would be a hidden field with default value before the select and an hidden option of the select field:
<html>
<head>
<body>
<form method="POST" action="">
<input type="hidden" name="dropdown" value="default" />
<select name="dropdown">
<option selected disabled hidden style="display: none" value="default"></option>
<option>1</option>
<option>2</option>
<input type="submit" value="send" />
</form>
</body>
</html>
Is $categoryTemp[$i] an ID or a name? If it is the ID and you are wanting to check the result against it to determine the default option to display then something along these lines would select the option that is equal to the value of $categoryTemp[$i].
<option <?php echo ($categorytemp[$i] == $education_category ? 'selected' : ''); ?>
So if $categorytemp[$i] = 1 and $education_category = 1 then that option would be marked selected and be displayed when the page loaded
This did the trick. When no value is selected, pass the default value as value in option
<select name="category" >
<option value='<?php echo $categorytemp[$i]?>'><?php echo $categorytemp[$i]; ?> </option>
<?php
$sql = "SELECT * FROM education_details";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result))
{
$education_category = $row["id"];
$education_name= $row["name"];
?>
<option value='<?php echo $education_category?>'><?php echo $education_name;?></option>
<?php
}
?>
</select>

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.

send the selected value from a dropdown menu to another page

I have a dropdownlist populated by a MySql database that shows the titles of books stored in my database.
<select id="titles">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
I want the option I choose to send it to another php page search.php
This search.php I want it to get the title and search for this specific book details.(title, price, author.... etc) .I tried to do it with but it ruins the page.
Add below code in form that should work for you.
<form action='search.php' method='post'>
<select id="titles" name='titles'>
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
<input type='submit' value='submit'>
</form>
in search.php:
$title = $_POST['titles'];
You just need to add the form above the select tag and need to give the NAME attribute in the select tag to post the data on another page. You can try with the following code:
<form method="post" action="search.php">
<select id="titles" name="titles">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
</select>
<input type="submit" name="submit"/>
</form>
and on the search.php page, you can get the value of the dropdown by this:
$title = $_POST['titles'];
Try as below :
<form method="post" action="YOURPAGEPATH">
<select id="titles">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
</select>
<input type="submit" name="submit"/>
</form>
Without submit button :
<form method="post">
<select id="titles" onchange="this.form.submit();">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
</select>
</form>
Surround that with a form with the appropriate action and add a submit button. Otherwise use something like jQuery to listen for the value of that to change and submit the form.
For example:
<form action="search.php" method="GET">
<select id="titles" name="title">
<?php /* put your stuff here */ ?>
</select>
</form>
And then in jQuery:
$(function(){
$('#titles').on('change', function(){
$(this).closest('form').submit();
});
});
Or you could go real old-school and attach the event listener to the select like this:
<form action="search.php" method="GET">
<select id="titles" name="title" onchange="this.parentNode.submit()">
<?php /* put your stuff here */ ?>
</select>
</form>
Just in case if you don't want to use the Submit Button
<script language="Javascript">
function books(book)
{
var url="http://www.example.com/search.php/?q="+book;
window.open(url, "_self");
}
</script>
<select id="titles">
<option value="emp" selected>Choose the title</option>
<?php
//drop down list populated by mysql database
$sql = mysql_query("SELECT title FROM book");
while ($row = mysql_fetch_array($sql))
{
echo '<option onClick="books('.$row['title'].')" value="'.$row['title'].'">'.$row['title'].'</option>';
}
?>
Here the list will call the Books function on Click and pass the arguments to the function which will redirect you to search.php
To retrieve the book name use
$_GET["q"]
Change the URL as required.
And if the problem is solved don't forget to Mark the answer.

keep php result as content in div

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

SQL and PHP - Submit form with an ID in URL (in wordpress)

I've been trying to find the best way to do this for a while now but cannot figure it out.
I have a simple dropdown which auto populates based on an SQL query. When you press "search" I need it to go to a page with the url extension ?id=x where x is the id of the option they selected.
$locations = $wpdb->get_results( $wpdb->prepare(
"SELECT * FROM wp_places_index WHERE visible='Y' ORDER BY place_name ASC") );
?>
<form id="find-buses-form" method="post" action="places_index.php">
<select class="default-value" type="text" name="from">
<option>Please select...</option>
<?php
foreach($locations as $location)
{
echo "<option>".$location->place_name."</option>";
// maybe this? echo "<input type=\"hidden\" name=\"id\">".$location->id."</input>";
}
?>
</select>
<input type="submit" name="submit" value="Show me" />
</form>
I think I may need to make it go to an external page which uses $_POST to pull that hidden field but I'd rather do it on one page.
I've achieved this before out of wordpress using something like this:
while ($row = mysql_fetch_array($result))
{
$picture = $row['Image'];
if($picture == ""){
$picture= "thumbnails/no-image-small.png";
}
$product_ID = $row["ProductID"];
But wordpress does not like the mysql_fetch_array :( Any advise?
You need to put whatever in a value attribute of your option tag. For example:
<?php
$locations = $wpdb->get_results( $wpdb->prepare(
"SELECT * FROM wp_places_index WHERE visible='Y' ORDER BY place_name ASC") );
?>
<form action="places_index.php" method="get">
<select name="x">
<?php foreach ($locations as $location): ?>
<option value="<?php echo $location->id; ?>"><?php echo $location->place_name; ?></option>
<?php endforeach; ?>
</select>
</form>
When submitted, the form will go to http://example.com/places_index.php?x=1 presuming the name of your select is x and the option selected has 1 in its value attribute.
Hope this helps.

Categories