I made some PHP code to generate this page. I successfully get all the items from a column into a HTML dropdown list (it's a dynamic list). I want to write some code so that when user selects an item from the list and hit submit, it will take user to a new page contains corresponding information on it. I have no idea what kind of code would be included in. Please help. Thanks!
For instance, if user select 50A-1, it will populate a table has all the items located at 50A-1.
Two pieces of code I wrote, first is the page gives you the dropdown list and the submit button. The second is the result page, but it only shows the whole inventory so far, it doesn't have a way to connect to the dropdown list option.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Inventory</title>
</head>
<body>
<div>
<a>SQL Connection test</a>
<form action="connect.php" method="POST">
<div class="center">
<input type="submit" value="Connect to MySQL" />
</div>
</form>
</div>
<div>
<section>
<article>
<p>
<select name="dropdown">
<?php query() ?>
</select>
<?php close() ?>
</p>
</article>
</section>
<div>
<input type="submit" value="Submit" />
</div>
</div>
</body>
</html>
Second page
<?php
include_once 'db.inc.php';
// connect
function connect() {
// Connect to the MySQL server
mysql_connect(DB_HOST,DB_USER,DB_PASS) or die ('Could not connect to server!' . mysql_error());
mysql_select_db(DB_NAME);
}
// close
function close() {
mysql_close();
}
// query
function query() {
$myData = mysql_query("SELECT DISTINCT * FROM sheet0_100 GROUP BY location");
while($record = mysql_fetch_array($myData)) {
echo '<option value="' . $record['location'] . '">' . $record['location'] . '</option>';
}
}
?>
That's the purpose of HTML forms :)
You need to create a form to encapsulate that select:
<form action="process.php" method="get">
<select name="inventory_id">
<!-- Here all options -->
</select>
<button type="submit">See items</button>
</form>
Then in process.php you need to get the selected element and query the database, for example (I assume that you're using PDO):
<?php
$inventory_id = $_GET['inventory_id'] // The name attribute of the select
// Then you prepare the query
$query = "SELECT * FROM sheet0_100 WHERE id = :inventory_id";
// Execute the query and show the data...
use Sessions
example:
on your first page
session_start();
$_SESSION['your-dropdown-list-value'] = 'Root';
on your new page
//error_reporting(E_ALL);
session_start();
if(isset($_SESSION['your-dropdown-list-value'])) {
echo "Your dropdown selection " . $_SESSION['your-dropdown-list-value'];
}
Related
Hi I'm trying to match a user id value from an input on a form to records in my database. I'm trying to show a column (itemname) of data in a dropdown select menu that match a userid value from a forms input. I don't know if I'm properly defining my variables or what im doing wrong but cant see what I'm missing. Any help is greatly appreciated. Thanks.
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
// Check if the connection failed
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
if (isset($_POST['userid']))
{
$userid= $_POST['userid'];
$query = "SELECT itemname
FROM seguin_orders
WHERE username = '".($userid)."'";
$result = mysqli_query($con,$query);
}
?>
FORM WITH DROPDOWN
<form action="xxx" method="post" name="form1">
<select name="xxx"><option value="">-- Select One --</option>
<?php
while ($row = mysqli_fetch_assoc($result))
{
echo '<option value =" ' . $row['itemname'] . ' ">' . $row['itemname'] . '</option>';
}
?>
</select>
<input id="input1" name="input1" type="text" />
</br>
<input id="userid" name="userid" type="text" value="demo#gmail.com" readonly="readonly"/>
<button type="submit" value="Submit">Submit</button>
</form>
==SOLUTION FOR AJAX FORM==
orders.php
<?php
// Create the connection to the database
$con=mysqli_connect("xxx","xxx","xxx","xxx");
// Check if the connection failed
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
if (isset($_GET['userid']))
{
$userid= $_GET['userid'];
$query = "SELECT itemname
FROM seguin_orders
WHERE username = '".($userid)."'";
$result = mysqli_query($con,$query);
while ($row = mysqli_fetch_assoc($result))
{
echo '<option value =" ' . $row['itemname'] . ' ">' . $row['itemname'] . '</option>';
}
}
?>
original page with form
This is just basic and simple, for you to understand. You can change it and make more secure. Please, read comments to understand
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form action="#">
<div class="pre-dropdown"> <!-- This class is here to hide this mini form after submit with jquery -->
<input type="text" name="userid" id="userid">
<button id="submitId">Submit Id</button>
</div>
<div class="dropdown"> <!-- This is hidden because there is no data, but when userid is submited, this will be visible -->
<select name="xxx" id="dropdown-select">
<option value="">-- Select One --</option>
</select>
</div>
</form>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(function(){
$('.dropdown').hide(); // Hide dropdown div when page is loaded, mbetter way will be with css, but it's enough for now
$('#submitId').on('click', function(e){ // Things to do when 'Submit Id' button is clicked
var userid = $('#userid').val(); // Grab user id from text field
e.preventDefault(); // Prevent form from submit, we are submiting form down with ajax.
$.ajax({
url: "orders.php",
data: {
userid: userid
}
}).done(function(data) {
$('.pre-dropdown').hide(); // Hide mini form for user id
$('.dropdown').show(); // show dropdown
$('#dropdown-select').append(data); // append results from orders.php to select
});
});
});
</script>
</body>
</html>
Change form the way you need. I am hidding pre-dropdown because if user submits userid again, we will append results twice.
You did two mistakes
You miss end of if condition ending }, and remove semicolon ; from while loop also string ending is missing.
In short you need a good IDE that can let tell you basic error in your code
Try Changing echo of your code to something like this-->
echo "<option value =\"". $row['itemname'] ."\">". $row['itemname'] . "</option>";
or try using mysqli_fetch_array() rather than mysqli_fetch_assoc()
And More Over change your sql query to something like this
$query = "SELECT itemname FROM seguin_orders WHERE username = '$userid'";
I'm trying to retrieve data from my database using and HTML form and php connection to my sql-workbench. I have a successful connection to the data base and my retrieval is posted at the top of my webpage. I'm not sure how to get it to run the sql query on the submit form function.
Any help would be appreciated, thanks.
<!DOCTYPE html>
<html>
<head data-gwd-animation-mode="quickMode">
<title>Test_webpage</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="generator" content="Google Web Designer 1.1.3.1119">
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "006";
$dbname = "mydb";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname);
//$con->close();
//$query = "SELECT * FROM US_Cars";
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$sql = "SELECT Manufacturer,VIN,Color,Model,Fuel_Type,State_of_Origin FROM mydb.US_Cars;";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Manufacturer: " . $row["Manufacturer"]. " VIN: " . $row["VIN"]. " Color:" . $row["Color"]. " Model:" . $row["Model"]. " Fuel Type:" . $row["Fuel_Type"]. " State Location:" . $row["State_of_Origin"]. "<br>";
}
} else {
echo "0 results";
}
?>
<div id="first">
<p>Enter Criteria Below to Search.</p>
</div>
<br>
<div id="second">
<p class="gwd-p-j2b6">Select a Manufacturer</p>
<!-- start of form -->
<form class="gwd-form-yuwo" method="post" action="<?search2.php ?>">
<select class="auto-style3 gwd-select-u9g0">
<option value="GM">GM</option>
<option value="Ford">Ford</option>
<option value="Chrysler">Chrysler</option>
<option value="Tesla">Tesla</option>
</select>appreaciated
<br>
<br>
<p class="gwd-p-cy97">Select a Dealership Location</p>
<select class="auto-style3 gwd-select-dkho">
<option value="">Virginia</option>
<option value="">Maryland</option>
<option value="">New Jesery</option>
<option value="">Kentucky</option>
</select>
<br>
<input type="submit" value="Submit" class="auto-style2">
</form>
</div>
<div id="third">
<img id="pic1" src="page2_1.jpg" style="width:500px;" height="236px" >
</div>
<div id="forth">
<img src="tesla.png" style="width:125px;height:250px">
</div>
<div id="fifth">
<footer>
<p>
U.S. Car data Entry
</p>
<p>
About Page
</p>
</footer>
</div>
</body>
</html>
<form class="gwd-form-yuwo" method="post" action="<?search2.php ?>">
is your issue.. pretty sure that is supposed to be
<form class="gwd-form-yuwo" method="post" action="search2.php">
which would send you to search2.php when the submit button was pressed... then in search2.php you would get your form values from $_POST and then run your query.
That being said I think that is not what you are trying to do and what you really want to do is update a list of things within the webpage without linking through. i.e. on button press update html at top of page to list query results using prams from form. If that is what you are trying to do you are way off and need to look up ajax... your submit button would not have a direct action but instead run a javascript fuction that would send an ajax request to search2.php that would run the query and then your java script would update innerhtml on response.
I have an html page that loads list of hotels in a select tag from a MySQL table using PHP. The select tag is inside a form tag. Whenever I load the page, the option tags will load, but when I submit my form, the option tags never load anymore. My form's action attribute is empty, I am checking everything on the same page, but when I put another php page as action, it loads normally. Is there a way to make it load after submit while keeping my form's action empty?
Here is my code
<?php
require_once 'db.php';
$db = DB::get_instance();
if(isset($_POST['search'])) {
$hotel = $_POST['hotel_list'];
$db->query("SELECT * FROM hotels WHERE Name='$hotel'");
$hotel = $db->result()->current();
$hid = $hotel['Hid'];
$db->query("SELECT * FROM rooms WHERE Hid='$hid'");
$rooms = $db->result();
$db->disconnect();
}
?>
<!doctype html>
<html>
<head>
<title>Display a hotel</title>
</head>
<body>
<form action="" method="post" id="dsphtl">
Name: <select name="hotel_list" form="dsphtl">
<?php
$db->query("SELECT Name FROM hotels ORDER BY Name");
foreach($db->result() as $row) {
$t = $row['Name'];
echo "<option value='$t'>$t</option>";
}
?>
</select>
<input type="submit" value="Search" name="search">
</form>
</body>
</html>
If $_POST['search'] is set, you $db->disconnect(); so it can't run the query in your form.
Take the $db->disconnect(); out of your if() statement, and put it at the end of the file.
The issue is with the disconnect, when the page reload after submit your connection to mysql lost due to
$db->disconnect();
<?php
require_once 'db.php';
$db = DB::get_instance();
if(isset($_POST['search'])) {
$hotel = $_POST['hotel_list'];
$db->query("SELECT * FROM hotels WHERE Name='$hotel'");
$hotel = $db->result()->current();
$hid = $hotel['Hid'];
$db->query("SELECT * FROM rooms WHERE Hid='$hid'");
$rooms = $db->result();
}
?>
<!doctype html>
<html>
<head>
<title>Display a hotel</title>
</head>
<body>
<form action="" method="post" id="dsphtl">
Name: <select name="hotel_list" form="dsphtl">
<?php
$db->query("SELECT Name FROM hotels ORDER BY Name");
foreach($db->result() as $row) {
$t = $row['Name'];
echo "<option value='$t'>$t</option>";
}
?>
</select>
<input type="submit" value="Search" name="search">
</form>
</body>
</html>
i am making a form with dynamically created checkboxes using from my database and some another static checkboxes how to reset the dynamically created checkboxes without affecting the static checkboxes here is my code...
<html>
<head>
<script>
function submit()
{
document.getElementById('form1').submit();
}
</script>
</head>
<body>
<form id="form1"method="get" name="form1">
<?php
mysql_connect('localhost','root','');
mysql_select_db('sample database');
$selectbrand="select brandname from brand group by brandname";
$resultbrand=mysql_query($selectbrand);
while($res=mysql_fetch_array($resultbrand))
{
$brands=$res['brandname'];
?>
<?php echo $brands?>:<input type="checkbox"name="<?php echo $brands?>"id="<?php echo
$brands?>" value="<?php echo $brands?>" onclick="submit();"<?php
if($_GET[$brands]):$ar[]=$_GET[$brands]?>checked="checked" <?php endif;?>><br>
<?php
}?>
<input type="reset" value="clear" name="reset1"value="clear">
<input type="checkbox"name="checkbox1" onclick="submit();" <?php
if($_GET['checkbox1']):?>checked="checked" <?php endif;?>>24 hrs
<input type="checkbox"name="checkbox2" onclick="submit();" <?php
if($_GET['checkbox2']):?>checked="checked" <?php endif;?>>2 days
<input type="checkbox"name="checkbox3" onclick="submit();" <?php
if($_GET['checkbox3']):?>checked="checked" <?php endif;?>>3 days
<input type="reset" name="reset2" value="clear">
</form>
</body>
</html>
<?php
$c=count($ar);
for($i=0;$i<$c;$i++)
{
mysql_connect('localhost','root','');
mysql_select_db('sample database');
$selectquery="select * from brand where brandname='$ar[$i] '";
$result=mysql_query($selectquery);
while($row=mysql_fetch_array($result))
{
$n=$row['brandname'];
echo $n;
}
}
?>
Easiest way to control one group of inputs is to incorporate Javascript and set a single class (or data-attributes) for that group. You can then attach an event to the faux-reset button and use Javascript to select only that class of inputs to reset.
See:
http://api.jquery.com/class-selector <-- how to select a group of elements with the same class, using jQuery
http://www.javascript-coder.com/javascript-form/javascript-reset-form.phtml <-- how to reset an entire form in pure Javascript
I'm not sure exactly where to implement the javascript because you didn't explain how you were going to use them but here is how I would accomplish it.
First put all the dynamically created id's into an array.
global $brandids;
while($res=mysql_fetch_array($resultbrand))
{
$brands=$res['brandname'];
$brandids[] = $brands; //this pushes the id into the brandids array
Next, you would have this php code write a complete javascript function or inside of one
$i = 0;
while ($brandids[$i] != null) {
echo 'document.getElementById("' . ($brandids[$i] . '").checked = false;';
$i++;
}
I am trying to fill a listbox on a webpage and I want the listbox to start blank. Once the button is clicked the listbox should populate. My code below automatically fills the listbox but I would rather have the button do it.
<?php
$dbc = mysql_connect('','','')
or die('Error connecting to MySQL server.');
mysql_select_db('MyDB');
$result = mysql_query("select * from tblRestaurants order by RestName ASC");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>SEARCH</title>
</head>
<body>
<form method="post" action="1004mcout.php">
<p><center>SEARCH</CENTER></P>
<select name="RestName">
<?php
while ($nt= mysql_fetch_assoc($result))
{
echo '<option value="' . $nt['RestID'] . '">' . $nt['RestName'] . '</option>';
}
?>
</select>
<p> SPACE</p>
<p>Click "SUBMIT" to display the calculation results</p>
<input type="submit" name="Submit" value="Submit" />
<br />
</form>
</body>
</html>
I would either: Preload the data into the page as some ready but invisible html list (maybe a bit n00b), or save the data as a javascript array and a function will load it into the page (better), or do an ajax call to the same page (for simplicity) (probably best, leaves you the option open for updated data after page initiation).
The Ajax route will have to use jQuery (change this_page.php to whichever page this is called):
<?php
while ($nt= mysql_fetch_assoc($result))
$arrData[] = $nt;
//If you want to test without DB, uncomment this, and comment previous
/*$arrData = array(
array('RestID' => "1", 'RestName' => "Mike"),
array('RestID' => "2", 'RestName' => "Sebastian"),
array('RestID' => "3", 'RestName' => "Shitter")
);*/
if(isset($_GET["ajax"]))
{
echo json_encode($arrData);
die();
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function displayItems()
{
$.getJSON("this_page.php?ajax=true", function(data) {
$.each(data, function(index, objRecord) {
var option=document.createElement("option");
option.value=objRecord.RestID;
option.text=objRecord.RestName;
$("#RestName").append('<option value="' + objRecord.RestID + '">' + objRecord.RestName + '</option>');
});
});
}
</script>
<title>SEARCH</title>
</head>
<body>
<form method="post" action="1004mcout.php">
<p><center>SEARCH</CENTER></P>
<select id="RestName"></select>
<p> SPACE</p>
<p>Click "SUBMIT" to display the calculation results</p>
<button type="button" onclick="javascript:displayItems();">Insert options</button>
<br />
</form>
</body>
</html>
Essentially, what it does, it collects the data, checks if there is a request for the ajax data in the url, if not, it prints the rest of the page (with an empty select). If there is an ajax flag in the url, then the php will encode the data into json, print that and stop.
When the User receives the page with an empty select, it clicks the button which will trigger the displayItems() function. Inside that function, it does a jQuery-based ajax call to the same page with the ajax flag set in the url, and the result (which is json), is evaluated to a valid javascript array. That array is then created into options and loaded into the RestName SELECT element.
A final cookie? You could just print the data as options, into the select anyway, just like the previous answers described. Then, inside the displayItems() function, you clear the select before loading it from the jQuery/ajax call. That way, the user will see data right from the beginning, and will only update this with the most recent data from the DB. Clean and all in one page.
<?php
$dbc = mysql_connect('','','')
or die('Error connecting to MySQL server.');
mysql_select_db('MyDB');
$result = mysql_query("select * from tblRestaurants order by RestName ASC");
?>
<html>
<head>
<script>
function displayResult()
{
var x =document.getElementById("RestName");
var option;
<?php
while ($nt= mysql_fetch_assoc($result))
{
echo 'option=document.createElement("option");' .
'option.value=' . $nt['RestID'] . ';' .
'option.text=' . $nt['RestName'] . ';' .
'x.add(option,null);';
}
?>
}
</script>
</head>
<body>
<select name="RestName">
</select>
<button type="button" onclick="displayResult()">Insert options</button>
</body>
</html>
Read more about adding options to select element from java script here
how about this simple way,
is this what you mean,
its not safe, any one can post show=yes but i think you just like users to be able to simply click and see result
<select name="RestName">
<?php
// if show=yes
if ($_POST['show'] == "yes"){
$dbc = mysql_connect('','','')
or die('Error connecting to MySQL server.');
mysql_select_db('MyDB');
$result = mysql_query("select * from tblRestaurants order by RestName ASC");
while ($nt= mysql_fetch_assoc($result))
{
echo '<option value="' . $nt['RestID'] . '">' . $nt['RestName'] . '</option>';
}
}
?>
</select>
<form method="post" action="#">
<input type="hidden" name="show" value="yes" />
<input type="submit" name="Submit" value="Submit" />
</form>
you can also simply use a hidden div to hid listbox and give the button an onclick action to show div, learn how in here: https://stackoverflow.com/a/10859950/1549838