PHP drop down coding question - php

Can someone show me how to make a If statement where if a drop down does not equal the default value of 0 (in my case) to automatically submit the form if possible?
session_start();
$current = isset($_SESSION['ClientNamefour']) ? $_SESSION['ClientNamefour'] : 0;
while ($row = mysql_fetch_array($result)) {
$id = $row["Client_Code"];
$thing = $row["Client_Full_Name"];
$value = "$id, $thing";
$sel=($id==$current)?'SELECTED':'';
$options4.="<OPTION $sel VALUE=\"$value\">$thing</option>";
}
?>
<FORM name="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<SELECT NAME="ClientNamefour" OnChange="this.form.submit()"
)">
<OPTION VALUE=0>Client
<?php echo $options4?>
</SELECT>
</FORM>

Use the onchange event and some JavaScript. In general your generated HTML should look something like this:
<form id="form" name="form" method="POST" action="http://example/script.php">
<select id="select" name="select" onChange="document.getElementById('form').submit();">
<option value="0" selected="selected">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
The onchange event is only fired when you select an unselected option, so no additional checks are required.
Compared with your solution:
the id is missing in your <form> tag
you need closing </option> tags
you'd probably need to change the JavaScript in the onchange attribute of the <select> tag

My understanding is that you can't replicate someone pushing a "submit" button using a server side language such as PHP. You could use javascript to submit the form if the user changes it (to something other than 0)
However, it looks like you only want the form to display if the SQL query returns a result that isn't 0?
In that case I'd do something like this...
Run your SQL Query
Code something like this:
if($option != 0){
//Function to do whatever happens after the form is sent (add to a database etc)
}
else{
//display the form
}

This is really sort of a javascript question... add an id attribute to your form like <form id="myfrm"...>, then after the </form> put:
<?php
if(((int) $_SESSION["your_session_variable"]) != 0){
?>
<SCRIPT language="javascript">
document.getElmenetById("myfrm").submit();
</SCRIPT>
<?ph } ?>

Related

Extract html input with php

I am new to php and want to make a dropdown menu where you can select a site that you want, then when you click a button you will be redirected to that site. The button will take you to for example "google.com" if that is what you select, if you select "stackoverflow.com" the same button will take you there. I currently have no working php code as I am not sure where to start. I will include the html code below.
<form method="post" action="testttt.php">
<select id="mySelect" onchange="myFunction()">
<option value="SelectSite"> Select Site Please
<option value="Itslearning"> Itslearning
<option value="NDLA"> NDLA
</select>
<input type="submit" value="GO"/>
The form ends a bit further down, so please don't complain about there being no :P ANY HELP IS APPRECIATED :)
Try the below code , i have done the example which you want and its work perfectly . You can do it this in single file as i have done .
<?php
if(isset($_POST['btnsubmit']))
{
$options = $_POST["testing"];
header('Location: '.$options.'');
echo "Your option value".$options;
}
?>
<form method="post" action="#">
<select id="mySelect" name="testing" onchange="myFunction()">
<option value="SelectSite"> Select Site Please
<option value="http://www.google.com"> Itslearning
<option value="http://www.stackoverflow.com"> NDLA
</select>
<input type="submit" name="btnsubmit" value="GO"/>
</form>
testttt.php will receive values in the $_POST array, so things like 'echo $_POST["somefield"];' will get you data...
...BUT you have to name your form elements. Not '<select id="somefield"...' but '<select name="somefield"...'. you can still have id attributes if you want, but pass to $_POST happens by what you put in the name= attribute.
Once you know the URL you're redirecting to, header("Location: $url");
Hope that gives you the push you need :-)
can you not just use the myfunction function like this:
function myfunction(event){
return window.open(event.target.options[event.target.options.selectedIndex].value,'');
}
If you want to do it in php, your select need a name attribute :
<form method="post" action="testttt.php">
<select id="mySelect" name="mySelect" onchange="myFunction()">
<option value="SelectSite"> Select Site Please
<option value="Itslearning"> Itslearning
<option value="NDLA"> NDLA
</select>
<input type="submit" value="GO"/>
</form>
You can do that either in PHP :
if(isset($_POST['mySelect']) && !empty($_POST['mySelect'])){
header('Location: ' . $_POST['mySelect']);
}
Or in Javascript using the onchange attribute you already set up :
myFunction(){
var target = event.target;
document.location.href(target.options[target.options.selectedIndex].value);
}

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.

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

php form select should trigger url change and value change

When I change the value of the select element, the
Page should load
The value based output should be echoed.
the url Should indicate the http://mysite.com/?sort=value
HTML
<form name="form1" action="" method="post">
<select id="filter1">
<option value="?sort=recent" onselected="this.form.submit();">Most recent</option>
<option value="?sort=views" onselected="this.form.submit();">Most viewed</option>
</select>
</form>
PHP
<?php
if(isset($_GET['filter1']))
{
$term = strtolower($_POST['filter1']);
switch($term)
{
case 'recent':
echo "recent";
break;
case 'views':
echo "by views";
break;
}
}
?>
Try
<form name="form1" action="newurl.php" method="post">
<select name="sort" onChange="this.form.submit();">
<option value="recent">Most recent</option>
<option value="views">Most viewed</option>
</select>
</form>
And remember your form method is post so the sort value will be stored on $_POST['sort']
Also, you can just change the form's method to "get" and leave the form's action value blank, since the default action behavior on post is to call the same file (let's call it form.php) with the get values attached (something like "form.php?sort=selectedvalue"), which already implies an url change, despite being the same file.
You seem to be a little confused about the process of sending data in forms. Here is the code which will work for you, based on your PHP file, and the variables it's looking to get from the querystring.
<form name="form1" action="" method="get">
<select id="filter1" name="filter1" onchange="this.form.submit();">
<option value="recent">Most recent</option>
<option value="views">Most viewed</option>
</select>
<input type="submit" value="Submit" />
</form>
You can see I've changed the method attribute to get. This means the data will be sent via the querystring, so once the form is submit the URL will change to: http://example.com/?filter1=value
Also for the sake of redundancy, you should include a submit button for people who have javascript turned off.
You have to use onChange event on your select object:
<form name="form1" action="" method="post">
<select name="filter1" onchange="parentNode.submit()">
<option value="recent">Most recent</option>
<option value="views">Most viewed</option>
</select>
</form>
The value of var filter1 on your PHP script will be recent or views, no need to use ?sort=whatever to send the data.
Then you must to retrieve the vars from you POST super-global, and not GET as you used. If you want to use GET you must change the method type on your form to get. I think using GET is the right way to do what you want.. so:
<?php
if(isset($_GET['filter1']))
{
$term = strtolower($_GET['filter1']);
switch($term)
{
case 'recent':
echo "recent";
break;
case 'views':
echo "by views";
break;
}
}
?>

php filter by dropdown without submit button

ive got the code below set up. but how do i filter the result without submit button and filtering the result based on dropdown value (id for user)?
form method="post" name="report_filter" action="<?= $_SERVER['PHP_SELF'];?>" >
select name="name" onchange="report_filter.submit();">
<option value="--">Filter by:</option>
<option value="1">Andi</option>
<option value="2">Katy</option>
<option value="3">Max</option>
<select>
PHP //
<? if(isset($_POST['submit'])):
$mem->StaffTodayFilterSummary($_GET('value'));
else :
$mem->StaffToday();
endif;
?>
</form>
You need to change name="report_filter" to id="report_filter".
Then change your onchange event to say onchange="document.getElementById('report_filter').submit()"
Here's the full code:
<form method="post" id="report_filter" action="<?= $_SERVER['PHP_SELF'];?>" >
<select name="name" onchange="document.getElementById('report_filter').submit();">
<option value="--">Filter by:</option>
<option value="1">Andi</option>
<option value="2">Katy</option>
<option value="3">Max</option>
<select>
<?
if(isset($_POST['name'])):
$mem->StaffTodayFilterSummary($_POST['name']);
else :
$mem->StaffToday();
endif;
?>
</form>
I changed isset() to check POST['name'] and set the filter summary to pass in $_POST['name'] as well. I don't know where $_GET('value') was trying to get anything from but unless it's in the URL I don't see how it would work.

Categories