Echo the selected items in drop down menus - php

I created two dropdown menu populated by two different database tables. I also created a button to press after having chosen something from the menu. What I would like to do (but I am not able to) is to print on the screen the selected items. Below the code I wrote until now:
<?php
require_once('assets/index.php');
$result1 = $conn->query("select * from partenze");
$result2 = $conn->query("select * from arrivi");
echo "<html>";echo "<body>";echo "<form action='index.php'>"; echo "Select your Departure: <select name='p_id'>";
while ($row1 = $result1->fetch_assoc()) {
unset($pid, $pname);
$pid = $row1['p_id'];
$plocalita = $row1['p_localita'];
echo '<option value="'.$pid.'">'.$plocalita.'</option>';}
echo "</select><br>";echo "Select your Arrival: <select name='a_id'>";
while ($row2 = $result2->fetch_assoc()) {
unset($aid, $aname);
$aid = $row2['a_id'];
$alocalita = $row2['a_localita'];
echo '<option value="'.$aid.'">'.$alocalita.'</option>';}
echo "</select>";
echo "<input type='submit' name='submit' value='Get Selected Values' />"; echo "</form>";
if(isset($_POST['submit'])){
$selected_val1 = $_POST['p_id']; // Storing Selected Value In Variable
$selected_val2 = $_POST['a_id']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val1. " and " .$selected_val2; // Displaying Selected Value
}
echo "</body>";echo "</html>";
?>

You are trying to retrieve data by $_POST data. but in form you haven't specify request method. So it will take get method by default. So you need to specify method=post in form to get request from POST
<?php
require_once('assets/index.php');
$result1 = $conn->query("select * from partenze");
$result2 = $conn->query("select * from arrivi");
echo "<html>";
echo "<body>";
echo "<form action='index.php' method='post'>";
echo "Select your Departure:
<select name='p_id'>";
while ($row1 = $result1->fetch_assoc()) {
unset($pid, $pname);
$pid = $row1['p_id'];
$plocalita = $row1['p_localita'];
echo '<option value="'.$pid.'">'.$plocalita.'</option>';}
echo "</select><br>";echo "Select your Arrival: <select name='a_id'>";
while ($row2 = $result2->fetch_assoc()) {
unset($aid, $aname);
$aid = $row2['a_id'];
$alocalita = $row2['a_localita'];
echo '<option value="'.$aid.'">'.$alocalita.'</option>';}
echo "</select>";
echo "<input type='submit' name='submit' value='Get Selected Values' />";
echo "</form>";
if(isset($_POST['submit'])){
$selected_val1 = $_POST['p_id']; // Storing Selected Value In Variable
$selected_val2 = $_POST['a_id']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val1. " and " .$selected_val2; // Displaying Selected Value
}
echo "</body>";echo "</html>";
?>

Related

Mapping values in dropdown 2 dependent on value selected in dropdwon 1 via php mysql

I am fresher in php & mysql.
I have a from where there are 2 dropdwon's. The value in dropdwon are coming via mysql. But now i am not able to get the value in 2nd dropdown dependent on value selected in 1st dropdown.
Here is the code i have tried so far.
Please Help!
Thank You
<html>
<head><title>Sheet</title></head>
<body>
<h2 align="center">SKU Selection</h2>
<?php
$conn=mysqli_connect('localhost','root','');
$db="sample";
mysqli_select_db($conn,$db);
$sql="SELECT DISTINCT(Site) FROM `bom`";
$result=mysqli_query($conn,$sql);
echo "Site Name :";
echo "<select name='Site'>";
echo "<option value='0'>Select Site</option>";
while($row=mysqli_fetch_array($result))
{
echo "<option value='".$row['Site']."'>".$row['Site']."</option>";
}
echo "</select>";
$sql1="SELECT BOM Desc FROM `bom` where Site= ";
$result1=mysqli_query($conn,$sql1);
echo "<br>";
echo "SKU :";
echo "<select name='SKU'>";
while($row1=mysqli_fetch_array($result1))
{
echo "<option value='".$row1['BOM Desc']."'>".$row1['BOM Desc']."</option>";
}
echo "</select>";
?>
</body>
</html>
Hi Your fixed code here:
<html>
<head><title>Sheet</title></head>
<body>
<h2 align="center">SKU Selection</h2>
<?php
$conn = mysqli_connect('localhost', 'root', '');
$db = "sample";
mysqli_select_db($conn, $db);
$sql = "SELECT DISTINCT(Site) FROM `bom`";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn)); // add error show info
echo "Site Name :";
echo "<select name='Site'>";
echo "<option value='0'>Select Site</option>";
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['Site'] . "'>" . $row['Site'] . "</option>";
}
echo "</select>";
$sql1 = "SELECT BOM Desc FROM `bom` where Site IS NULL "; // change the for null site
$result1 = mysqli_query($conn, $sql1) or die(mysqli_error($conn)); // add error show info
echo "<br>";
echo "SKU :";
echo "<select name='SKU'>";
while ($row1 = mysqli_fetch_array($result1)) {
echo "<option value='" . $row1['BOM Desc'] . "'>" . $row1['BOM Desc'] . "</option>";
}
echo "</select>";
?>
</body>
</html>
And if you need load on second select php only cant handle this because you must give time to user for check first select.
I think the better way is using Ajax request for second:
Auto Load Second Dropdown using AJAX
I suggest to use in both <select> the clause selected to show the selected <option>.
Then, in the first <select> add the on change event to launch a page refresh so that:
The selected entry is recognised as selected
The SQL for the second drop-down can be filtered on the selected entry in first dropdown
The first select should appear then like this:
<select onChange='if(options[selectedIndex].value) { location=options[selectedIndex].value;}' size='1'>
<option value='?site=Plant1'>Plant ONE</option>
<option value='?site=Plant2' selected>Plant 2</option>
</select>
When Plant 2 is selected, the page will be refreshed with the URL containing the parameter &site=Plant2 which you can read in the variable $_REQUEST['site'] to be used in the 2nd SQL query

HTML/PHP Form Select Option with link to MySQL

I followed a previous question on here to get a drop down with link to MySQL. It works without the form but with the form, all the room_id's just scatter across one line and don't go in a drop down box. Any ideas on how to fix it? Thank you
//Creates a form for room_id
echo "<form action=''>";
echo "<select name='room_id'>";
//Creates drop down box to show the current rooms vacant
$sql = "SELECT * FROM room";
$sql.= " WHERE room_vacant = 1";
$stmt = $dbh->query($sql);
echo "<select name='room_id'>";
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['room_id'] . "'>" . $row['room_id'] . "</option>";
} //Closes drop down box
echo "</select>";
//Submit button
echo "<input type='submit' value='Submit'>";
//Closes form
echo "</form>";
The reason is that you are echoing your select twice. Remove one.
//Creates a form for room_id
echo "<form action=''>";
echo "<select name='room_id'>";
//Creates drop down box to show the current rooms vacant
$sql = "SELECT * FROM room";
$sql.= " WHERE room_vacant = 1";
$stmt = $dbh->query($sql);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['room_id'] . "'>" . $row['room_id'] . "</option>";
} //Closes drop down box
echo "</select>";
//Submit button
echo "<input type='submit' value='Submit'>";
//Closes form
echo "</form>";

Search Data not outputting the correct results

This form is a search form which allows the user to search for an event using the Venue and category fields which are scripted as dropdown boxes and the Price and event title as user input text boxes, as shown via the code if a keyword is entered which matches the fields on the database it should output all the related information for that event if any matches have been made on either search fields, the tickboxes allow the user to identify what criteria they would like to search with, if the tickbox field hasn't been checked then the SQL enquiry will not search for keywords with that corresponding field.
The issue is, it all seems to work fine except no results seem to show up for the Venue and Category fields if they was solely used to search for an event. But if I choose another field everything is outputting correctly including the venue and Category field.
DATABASE: http://i.imgur.com/d4uoXtE.jpg
HTML FORM
<form name="searchform" action ="PHP/searchfunction.php" method = "post" >
<h2>Event Search:</h2>
Use the Check Boxes to indicate which fields you watch to search with
<br /><br />
<h2>Search by Venue:</h2>
<?php
echo "<select name = 'venueName'>";
$queryresult2 = mysql_query($sql2) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult2)) {
echo "\n";
$venueID = $row['venueID'];
$venueName = $row['venueName'];
echo "<option value ='$venueName'";
echo ">$venueName</option>";
}# when the option selected matches the queryresult it will echo this
echo "</select>";
echo" <input type='checkbox' name='S_venueName'>";
mysql_free_result($queryresult2);
mysql_close($conn);
?>
<br /><br />
<h2>Search by Category:</h2>
<?php
include 'PHP/database_conn.php';
$sql3 ="SELECT catID, catDesc
FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysql_query($sql3) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult3)) {
echo "\n";
$catID = $row['catID'];
$catDesc = $row['catDesc'];
echo "<option value = '$catDesc'";
echo ">$catDesc </option>";
}
echo "</select>";
mysql_free_result($queryresult3);
mysql_close($conn);
?>
<input type="checkbox" name="S_catDes">
<br /><br />
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br /><br />
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br /><br />
<input name="update" type="submit" id="update" value="Search">
</form>
PHP CODE THAT DEALS WITH PROCESSING THE FORM DATA
<?php
include 'database_conn.php';
$venuename = $_POST['venueName']; //this is an integer
$catdesc = $_POST['catdesc']; //this is a string
$Price = $_POST['S_price'];
$EventT = $_POST['S_EventT'];
#the IF statements state if the tickbox is checked then search with these enquires
if (isset($_POST['S_VenueName'])) {
$sql = "SELECT * FROM te_venue WHERE venueName= '$venuename'";
}
if (isset($_POST['S_catDes'])) {
$sql = "SELECT * FROM te_category WHERE catID= '$catdesc'";
}
if (isset($_POST['S_CheckPrice'])) {
$sql = "SELECT * FROM te_events WHERE (eventPrice LIKE '%$Price%')";
}
if (isset($_POST['S_EventTitle'])) {
$sql = "SELECT * FROM te_events WHERE (eventTitle LIKE '%$EventT%')";
}
$queryresult = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult))
{
echo "Event Title: "; echo $row['eventTitle'];
echo "<br />";
echo "Event Description: "; echo $row['eventDescription'];
echo "<br />";
echo "Event Venue "; echo "$venuename";
echo "<br />";
echo "Event Category "; echo "$catdesc";
echo "<br />";
echo "Event Start Date "; echo $row['eventStartDate'];
echo "<br />";
echo "Event End Date "; echo $row['eventEndDate'];
echo "<br />";
echo "Event Price "; echo $row['eventPrice'];
echo "<br /><br />";
}
mysql_free_result($queryresult);
mysql_close($conn);
?>
Try using atleast MySQLi instead of deprecated MySQL. You can try this:
database_conn.php:
<?php
/* ESTABLISH YOUR CONNECTION. REPLACE THE NECESSARY DATA BELOW */
$con=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
HTML Form:
<html>
<body>
<?php
include 'PHP/database_conn.php';
$sql2="SELECT venueID, venueName FROM te_venue"; /* PLEASE REPLACE THE NECESSARY DATA */
echo "<select name = 'venueName'>";
$queryresult2 = mysqli_query($con,$sql2);
while($row = mysqli_fetch_array($queryresult2)) {
echo "\n";
$venueID = mysqli_real_escape_string($con,$row['venueID']);
$venueName = mysqli_real_escape_string($con,$row['venueName']);
echo "<option value ='$venueName'>";
echo $venueName."</option>";
} /* when the option selected matches the queryresult it will echo this ?? */
echo "</select>";
echo "<input type='checkbox' name='S_venueName'>";
?>
<br><br>
<h2>Search by Category:</h2>
<?php
$sql3 ="SELECT catID, catDesc FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysqli_query($con,$sql3);
while($row = mysqli_fetch_array($queryresult3)) {
echo "\n";
$catID = mysqli_real_escape_string($con,$row['catID']);
$catDesc = mysqli_real_escape_string($con,$row['catDesc']);
echo "<option value = '$catDesc'>";
echo $catDesc."</option>";
}
echo "</select>";
?>
<input type="checkbox" name="S_catDes">
<br><br>
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br><br>
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br><br>
<input name="update" type="submit" id="update" value="Search">
</form>
</body>
</html>
PHP:
<?php
include 'database_conn.php';
$venuename = mysqli_real_escape_string($con,$_POST['venueName']); /* this is an integer */
$catdesc = mysqli_real_escape_string($con,$_POST['catdesc']); /* this is a string */
$Price = mysqli_real_escape_string($con,$_POST['S_price']);
$EventT = mysqli_real_escape_string($con,$_POST['S_EventT']);
/* SHOULD PRACTICE USING ESCAPE_STRING TO PREVENT SOME OF SQL INJECTIONS */
/* the IF statements state if the tickbox is checked then search with these enquires */
if (isset($_POST['S_VenueName'])) {
$sql = "SELECT * FROM te_venue WHERE venueName= '$venuename'";
}
if (isset($_POST['S_catDes'])) {
$sql = "SELECT * FROM te_category WHERE catID= '$catdesc'";
}
if (isset($_POST['S_CheckPrice'])) {
$sql = "SELECT * FROM te_events WHERE (eventPrice LIKE '%$Price%')";
}
if (isset($_POST['S_EventTitle'])) {
$sql = "SELECT * FROM te_events WHERE (eventTitle LIKE '%$EventT%')";
}
$queryresult = mysqli_query($con,$sql);
while ($row = mysqli_fetch_array($queryresult))
{
echo "Event Title: "; echo $row['eventTitle'];
echo "<br />";
echo "Event Description: "; echo $row['eventDescription'];
echo "<br />";
echo "Event Venue "; echo "$venuename";
echo "<br />";
echo "Event Category "; echo "$catdesc";
echo "<br />";
echo "Event Start Date "; echo $row['eventStartDate'];
echo "<br />";
echo "Event End Date "; echo $row['eventEndDate'];
echo "<br />";
echo "Event Price "; echo $row['eventPrice'];
echo "<br /><br />";
}
mysqli_close($conn);
?>
What if user checks all the check box? What would happen is, the last condition will be used. The first three conditions will be overwritten by the last condition.
If you use ELSE IF in those conditions, the first condition will be implemented.
My advice is to use radio button instead of check box and hope you gets the idea along the way.
Have you tried printing out your $sql query for debugging?
Try <input type="checkbox" name="S_catDes" value="checked">.
From memory checkboxes need a value field but I could be wrong. Hope this helps.

Passing dropdown list value to another SELECT statement on same page

Hi and thanks for looking at this with me. I am COMPLETELY new to using PHP to run MySQL select statements. That being said, I have managed to run a SELECT statement to populate a drop down list...and another SELECT statement to populate an HTML table. (this is for a roleplaying game)
But this is where3 I get stuck...
I would like for the dropdown selected value to be the "WHERE racename = " value in the second select statement that populates the table so that only one row is returned instead of all the data.
Here's the page: http://www.gamehermit.com/racechoice.php
Here's my code so far:
<?php
// Make a MySQL Connection
mysql_connect("localhost", "db_username", "password") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query="SELECT * FROM Races";
$result = mysql_query($query);
echo "<select name=racename>";
while($nt=mysql_fetch_array($result))
{
if ($nt[racename]==$_POST["racename"])
$selected="selected";
else
$selected="";
echo "<option ".$selected."value=$nt[racename]>$nt[racename]</option>";
}
echo "</select>";
echo "<br />";
// Get all the data from the "Race" table and create table
$result2 = mysql_query("SELECT * FROM Races")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Race Name</th> <th>Might Modifier</th> <th>Valor Modifier</th> <th>Deftness
Modifier</th> <th>Insight Modifier</th> <th>Dweomer Modifier</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result2 )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['racename'];
echo "</td><td>";
echo $row['modmight'];
echo "</td><td>";
echo $row['modvalor'];
echo "</td><td>";
echo $row['moddeftness'];
echo "</td><td>";
echo $row['modinsight'];
echo "</td><td>";
echo $row['moddweomer'];
echo "</td></tr>";
}
echo "</table>";
?>
I hope this is simple...thanks so much :)
~ Jack
The best way to do so is to use AJAX so you don't need to pass variables and load a new page.
But here's how you can do it with the old-fashioned way:
assume you will be having only one page and you will pass the selected value to the same page (a page reload is required)
so let's say your page is game.php
you need to include in this page a "jump menu" with a submit button to be pressed after the user selects something from the list
in the header of your page you need to check if the button was pressed using the
if(isset($_POST['button_name'])) {
// button pressed.. perform next step and select your new data to fill the table
} else {
// nothing pressed and nothing to be performed load the page normally
}
inside the "true" of the "if" you need here to get the passed variable from the list for example
$var = $_POST['list_name'];
so now you have the second variable to select the required data to fill the table.
a complete code should look something similar to the following, game.php:
<?php
if(!isset($_POST['go_button'])){ //option not selected display list to choose from
// Make a MySQL Connection
mysql_connect("localhost", "db_username", "password") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
$query="SELECT * FROM Races";
$result = mysql_query($query);
$num = mysql_numrows($result);
?>
<script type="text/javascript">
function MM_jumpMenuGo(objId,targ,restore){ //v9.0
var selObj = null; with (document) {
if (getElementById) selObj = getElementById(objId);
if (selObj) eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
if (restore) selObj.selectedIndex=0; }
}
</script>
<form name="form" id="form" action="game.php" method="post">
<select name="jumpMenu" id="jumpMenu">
<?php $i=0; while($i<$num) { ?>
<option value="<?php echo mysql_result($result,$i,'racename_field_value'); ?>"><?php echo mysql_result($result,$i,'racename'); ?></option>
<?php } ?>
</select>
<input type="button" name="go_button" id= "go_button" value="Go" onClick="MM_jumpMenuGo('jumpMenu','parent',0)">
</form>
<?php
echo "<br />";
} else { //option selected to get the variable and use it to select data from DB
$var= $_POST['jumpMenu'];
// Get all the data from the "Race" table and create table
$result2 = mysql_query("SELECT * FROM Races WHERE racename='$var'")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Race Name</th> <th>Might Modifier</th> <th>Valor Modifier</th> <th>Deftness
Modifier</th> <th>Insight Modifier</th> <th>Dweomer Modifier</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result2 )) {
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['racename'];
echo "</td><td>";
echo $row['modmight'];
echo "</td><td>";
echo $row['modvalor'];
echo "</td><td>";
echo $row['moddeftness'];
echo "</td><td>";
echo $row['modinsight'];
echo "</td><td>";
echo $row['moddweomer'];
echo "</td></tr>";
}
echo "</table>";
}
?>
I modified your code and added something to get you start with, excuse me if there was any error when trying to load the page i wrote it without trying it
good luck!

Drop down list filter triggered by submit button

I have made a filter function but I am having trouble with the starting table, I want all the data selected from a table to be displayed if no category is selected for the filter. So far, I can show all the necessary data needed if a category is chosen but only if a category is chosen. If none is chosen, it shows a blank table. Help please,...
Here's the function
function listhistoryHost(){
$accountid=$_SESSION['userid'];
if(isset($_POST['button'])){
$filter=$_POST['historyfilter'];
if($filter==$filter){
$sql="select * from webhostrequest where status='$filter' order by webhostrequest.recentact desc";
$result=mysql_query($sql) or die("Error in selecting items ".mysql_error());
$out="<ul>";
while($row=mysql_fetch_array($result)){
$accountid=$row['userid'];
$requesttitle=$row['requesttitle'];
$requestid=$row['requestid'];
echo "<table width=\"100%\" border=\"0\" cellpadding=\"2\">";
echo "<tr class=\"rowcolor1\">";
echo "<td width=\"70%\"><span style=\"padding-left:20px\">Requested Web Hosting for ".$row["requesttitle"]. "</td>";
echo "<td width=\"20%\"><span style=\"padding-left:20px\">Status: " .$row["status"]. "</td>";
echo "<td>
<center>
<form id = \"form1\" method = \"post\" action = \"viewhistorywebhost.php?webhost=$requestid\">
<input type = \"submit\" name = \"button\" id = \"button\" value = \"Details\" />
</form>
</center>";
echo "</tr>";
}
echo "</table>";
return $out;
}
}
}
Here's the form and trigger
<form id = "form1" method = "post" action = "#">
<select id="select1" name="historyfilter">
<option value='' selected disabled>Select item type</option>
<?php
$options = array('approved' => 'Approved',
'cancelled'=>'Cancelled',
'rejected' => 'Rejected');
foreach($options as $value => $type){
echo "<option value=\"$value\">$type</option>";
}
?>
</select>
<input type = "submit" name = "button" id = "submit" value = "Go" />
</form>
<?php
$webhost=new requisition2();
echo $webhost->listhistoryHost();
?>
Just put if condition for query
function listhistoryHost(){
$accountid=$_SESSION['userid'];
if(isset($_POST['button'])){
$filter=$_POST['historyfilter'];
$sql="select * from webhostrequest order by webhostrequest.recentact desc";
if(isset($filter))
$sql="select * from webhostrequest where status='$filter' order by webhostrequest.recentact desc";
$result=mysql_query($sql) or die("Error in selecting items ".mysql_error());
$out="<ul>";
while($row=mysql_fetch_array($result)){
$accountid=$row['userid'];
$requesttitle=$row['requesttitle'];
$requestid=$row['requestid'];
echo "<table width=\"100%\" border=\"0\" cellpadding=\"2\">";
echo "<tr class=\"rowcolor1\">";
echo "<td width=\"70%\"><span style=\"padding-left:20px\">Requested Web Hosting for ".$row["requesttitle"]. "</td>";
echo "<td width=\"20%\"><span style=\"padding-left:20px\">Status: " .$row["status"]. "</td>";
echo "<td>
<center>
<form id = \"form1\" method = \"post\" action = \"viewhistorywebhost.php?webhost=$requestid\">
<input type = \"submit\" name = \"button\" id = \"button\" value = \"Details\" />
</form>
</center>";
echo "</tr>";
}
echo "</table>";
return $out;
}
}
You need to check out a $filter for empty
if (empty($filter)) {
$sql="select * from webhostrequest order by webhostrequest.recentact desc";
} else {
$sql="select * from webhostrequest where status='$filter' order by webhostrequest.recentact desc";
}

Categories