I want to pass a select option value through hyperlink to the next page and for this I have this code:
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<form name="search_form" role="form" method="GET" id="search_form" action="SearchResults.php">
<?php
try {
$conn = new PDO('sqlite:db/MyDatabase.db');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM attributes WHERE attributename='mushtype'");
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<select id="mushtype" name="mushtype">
<option value="*" selected>Mushroom types</option>
<?php foreach($data as $row): ?>
<option value="<?php echo $row['idattributevalue']; ?>"><?php echo $row['attributevalueEN']; ?></option>
<?php endforeach; ?>
</select>
<?php
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
Find Your Mushroom
</form>
</body>
</html>
For the default selected option I want to use (*) as value because if no option are selected, will stand as SELECT (all) FROM for my SQL query on the second page.
So, i tried to construct my hyperlink, but i don't know how to catch the selected option.
I tried to adapt from here
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['Movies'])) {
$selected = $_POST['Movies'];
echo 'You have chosen: ' . $selected;
} else {
echo 'Please select the value.';
}
}
?>
but I'm unable to do it.
Rigth now, my code inserting a value, but is without any control upon it.
Please help me to catch the selected option and insert it as value in my hyperlink. Thank you.
When you use <a>, you do not submit the inputs to the next page. Instead of
Find Your Mushroom
simply use
<input type="submit" value="Find Your Mushroom">
before closing the form.
Edit:
Depending on the <form method= you use ("get" or "post"), you will then either have $_GET['mushtype'] or $_POST['mushtype'] available in the next page. (Thanks to #ADyson!)
In my tests using method="get", the form inputs make their way to $_GET, but my uri parameters were not there. Using method="post" gave me both my uri parameters in $_GET and form details in $_POST, just in case you want to use both.
If you do not like the button style however, you can change it using CSS to look just like a regular hyperlink.
Related
<?php
$connect = mysqli_connect("localhost", "root", "jmpmvp", "characters");
if ($connect){
echo "connected<br>";
}
$query = "SELECT * FROM `character`";
$result1 = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action ="handler.php" method="post">
<label for="character">SELECT A CHARACTER </label>
<select multiple name="character">
<?php while($character = mysqli_fetch_assoc($result1)){?>
<option value ="<?php echo $character['id'];?>"</option>
<?php echo $character['name'];?></option>
<?php }?>
<input type="submit" value="submit"/>
</select>
</form>
</body>
</html>
this is my index page above
<?php
$connect = mysqli_connect("localhost", "root", "jmpmvp", "characters");
if ($connect){
echo "connected<br>";
}
$query = "SELECT * FROM `character` where id = ". $_POST ["character"];
$result1 = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php while($character = mysqli_fetch_assoc($result1)){?>
<?php echo $character["name"];?><br>;
<?php echo $character["attack"];?><br> ;
<?php echo $character["defense"];?><br>;
<?php } ?>
</body>
</html>
alright here is my handler page the issue I am having is I can select multiple options in my html select on my index page but I am having a problem displaying when multiple characters are selected in my handler page. Does anyone know how to fix this specific issue? I also want the data to displayed in a table which I'm pretty sure I can figure out.
What You actually need is logical approach. You have to ask yourself a question "what You want", "what You need" and "how to do it".
So in Your case You want to compare something but You didn't actually say what exactly You need. So if You're new i can can help You that:
What You need for sure is webpage, where user can select character from a list. But what then? I don't know. You didn't specify so...:
1) Show user a select box to choose character. How to get them? Select from database. This is what You already have.
2) After user select character You need to send this data to the server. How to do it? Use <form> tag like:
<form method="post">
<select name="character">...option list...</select>
<input type="submit" value="Search">
</form>
3) Get data sent by Your form and use them to compare with... something You have.
<?php
if( isset( $_POST['character'] ) ){
// do something with this character
}
?>
4) Show user response like found or not found or something else. Pass this data into some div like:
<?php
$found = 'set this true OR false';
if( $found ){
$message = 'Found it!';
}else{
$message = 'Not_found!";
}
?>
Then in HTML write something like:
<div><?php echo isset( $message ) ? $message : ''; ?></div>
Thats it, rest is up to You. Any simple problem You will solve by searching in Google.
-------- Edit
First of all if You're using multiple select box, the name must be:
<select name="character[]" multiple>
Then Your $_POST['character'] is now an array. You can check its content by:
echo '<pre>';
var_dump($_POST);
echo '</pre>';
Use foreach:
$ids = []; // or $ids = array(); if php version lower than 5.4
foreach( $_POST['character'] as $v ){
$ids []= (int) $v;
}
$query = 'SELECT * FROM `character` where id IN ('. implode(',', $ids) .') ';
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'];
}
hey guys i've passed way more time on this then what i originally wanted to...
so i have this code here, where i have a drop list give me data from a sql database from the selection of 3 radio buttons, that all works fine.
My problem come when i want to submit my form and get info of the data in said droplist. all i want is put the selected radio and the selected item in the single drop list in variables in the submission.php that comes after the post method of the form...
anyway thats what i want to do for now
<?php
require "../Scripts/config.php"; // database connection here
?>
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>test</title>
<SCRIPT language=JavaScript>
function reload()
{
for(var i=0; i < document.form1.type.length; i++){
if(document.form1.type[i].checked)
var val=document.form1.type[i].value
}
self.location='bob.php?type=' + val ;
}
</script>
</head>
<body>
<?Php
$tp=$_GET['type']; // getting the value from query string
if(strlen($tp) > 1){$sql="SELECT * FROM Subcategory where cat_id='$tp'";}
echo $sql;
echo "<form name=form1 id=form1 method=post action=submissions2.php>";
echo "<select name=Subcategory id=Subcategory value=''>Subcategory</option>"; // printing the list box select command
foreach ($dbo->query($sql) as $row){//Array or records stored in $row
echo "<option value=$row[cat_id]>$row[Subcategory]</option>";
/* Option values are added by looping through the array */
} echo "</select>";// Closing of list box
echo "<br>";
echo "<br>";
echo "<br>";
echo "
<b>Type</b>
<input type=radio name=type value='1_Cosplay' onclick=\"reload()\";>Cosplay
<input type=radio name=type value='1_Modeling' onclick=\"reload()\";>Modeling
<input type=radio name=type value='1_Zombie' onclick=\"reload()\";>Zombie
<input type=submit value=Submit> </form>";
echo "<br>";
echo "<br>";
echo "<br>";
?>
</body>
</html>
and this is the submissions2.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="../Scripts/jquery-1.8.0.min.js"></script>
</head>
<body>
<?php
function filter($data) {
/*$data = trim(htmlentities(strip_tags($data)));
if (get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);*/
return $data;
return $row;
}
foreach($_POST as $key => $value) {
$mydata[$key] = filter($value);
}
echo $mydata['Subcategory'];
echo "<br>";
?>
</body>
</html>
all i seem to be able to get is the radio button choice.
Here is an all-in-one solution. You need to change some references like what the name/local path of the file path is, but anyway, this contains all the code. I can not test the DB stuff but the ajax works if you have the correct url path in the jQuery portion. Note, this solution references itself, not a new page:
// Display errors for troubleshooting
ini_set('display_errors','1');
error_reporting(E_ALL);
class CategorySelector
{
public function LoadSubCat()
{
// You will be subjected to an injection hack if you don't filter or encode this variable
// You should do PDO with prepared statements
$parent_cat = htmlspecialchars($_GET['parent_cat'], ENT_QUOTES);
$query = $this->Fetch("SELECT id,subcategory_name FROM subcategories WHERE categoryID = '$parent_cat'");
// Uncomment this to see how this returns
// $this->PrintPre($query); ?>
<label for="sub_cat">Sub Category</label>
<select name="sub_cat" id="sub_cat">
<?php
if($query !== 0) {
foreach($query as $row) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['subcategory_name']; ?></option>
<?php
}
} ?>
</select>
<?php
}
public function Form()
{
// Get rows for categories
$results = $this->Fetch("SELECT id,category_name FROM categories");
// Uncomment this to see how this returns
// $this->PrintPre($results); ?>
<form name="form1" id="form1" method="post">
<label for="parent_cat">Parent Category</label>
<select name="parent_cat" id="parent_cat">
<?php
if($results !== 0) {
foreach($results as $row) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['category_name']; ?></option>
<?php }
} ?>
</select>
<!-- This is a container that will load in your next menu -->
<div id="sub_cat_container"></div>
<input type="submit" name="submit" value="submit" />
</form>
<?php
}
public $rowCount;
// This is strictly a returning engine for SQL statements
protected function Fetch($_sql)
{
include_once('config.php');
// You really should do prepared statements (PDO)
// This way of calling sql is depricated
$query = mysql_query($_sql);
// Save the row count
$this->rowCount = mysql_num_rows($query);
// If there are rows return them
if($this->rowCount > 0) {
$_array = array();
// Loop through
while($result = mysql_fetch_array($query)) {
$_array[] = $result;
}
}
// Send back your query results for processing
// If no results, return false/0
return (isset($_array))? $_array:0;
}
protected function PrintPre($_array)
{ ?>
<pre>
<?php print_r($_array); ?>
</pre>
<?php
}
}
// Uncomment this for testing that the AJAX is working.
// print_r($_REQUEST);
// This is probably not the best way to do this all, but for sake
// of trying to get it all to work, this whole thing will ajax to
// itself, but if you can get it to work on this one page, you
// can split it up into two pages.
// Ok, so this creates a new instance of this whole system
$builder = new CategorySelector();
// If this page receives a GET request for $_GET['parent_cat'], just process it.
// That action is to call the sub_cat dropdown menu from this object
if(isset($_REQUEST['parent_cat']) && !empty($_REQUEST['parent_cat'])) {
$builder->LoadSubCat();
}
// If there is no request, display the html page
else {
// You should not have space before the <!doctype>. Some browsers act funky if there is space before
?><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dependent DropDown List</title>
<script type="text/javascript" src="jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript">
// I'm not a javascript person, so this portion is kind of sloppy
$(document).ready(function(){
$('#parent_cat').change(function() {
// Get value
var ElmVal = $('#parent_cat').val();
$.ajax({
// You need to reference this page in the "thispage.php" whatever this page is called
url:"/thispage.php?parent_cat="+ElmVal,
success:function(result) {
$("#sub_cat_container").html(result);
}});
});
});
</script>
</head>
<body>
<?php
// Display the form.
$builder->Form(); ?>
</body>
</html>
<?php } ?>
Quote all your HTML attributes like name='Subcategory', and
echo "<option value=$row[cat_id]>$row[Subcategory]</option>"
should be
echo "<option value='{$row['cat_id']}'>{$row['Subcategory']}</option>";
Your coding practice is horrible, by the way. You are not testing to see how many rows you have in your MySQL query, and you don't need to echo on each line. You can do this:
echo '<br />'.
'<br />';
Of course, using line breaks like that is a bad practice, as well. Use CSS.
using select list with mysql created a list. I have a mysql data with c_code,Table center,and having data 1. id,2. name,3. code. i want to select name from mysql data after selecting name in data list want to show the code crosponding that name without using any submit button from select dropdown list, and the code shows in either label or in inputtext box.
Here is my full code.
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 1</title
</head>
<body>
<form id="form1" name="form1" action="" , method="post" >
<div>
<label for="list">Center</label>
<select name="list">
<option value=''>-----SELECT-----</option>
<?php
$conn = mysqli_connect('localhost', 'root', '');
$result = mysqli_query($conn, 'SELECT id,name,code FROM center');
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='$row[id]'>$row[name]</option>";
}
?>
</select>
</div>
</form>
</body>
</html>
First, let's organize the code a bit...
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled 1</title>
</head>
<body>
<form id="form1" name="form1" action="" method="post">
<div>
<label for="list">Center</label>
<select name="list">
<option value=''>-----SELECT-----</option>
<?php
$conn=mysqli_connect('localhost','root','');
$result=mysqli_query($conn,'SELECT id,name,code FROM center');
while($row=mysqli_fetch_assoc($result)) {
echo "<option value='$row[id]'>$row[name]</option>";
}
?>
</select>
</div>
</form>
</body>
</html>
Second, dynamically doing anything in HTML is impossible with PHP, PHP is a server-side script and can not post back data after user manipulations without refreshing the page.
You are looking for an $.ajax(); solution. I'd suggest looking into it on http://api.jquery.com/jQuery.ajax/
Good luck!
you should write select tag out of form
because this list will not populated until form submitting
Hope its this what you need. you do a select on the id and name for the dropdown menu. after you selected an element the form ll be submitted and a new sql query ll return you the code. there are several other ways to return the code, this is just one easy way
notice, i didnt use prepared statements! because i do not have the correct synatx in head right now... you should think about a general implementation of prepared statements.
<form id="form1" name="form1" action="" method="post" >
<div>
<label for="list">Center</label>
<select name="list" onchange="this.form.submit()">
<option value=''>-----SELECT-----</option>
<?php
$conn = mysqli_connect('localhost', 'root', '');
$result = mysqli_query($conn, 'SELECT id,name FROM center');
while ($row = mysqli_fetch_assoc($result))
{
$selected = (isset($_POST['list']) && $_POST['list'] == $row['id']) ? 'selected' : '';
echo "<option value='$row[id]' $selected >$row[name]</option>";
}
?>
</select>
</div>
<div>
<?php
if (isset($_POST['list']))
{
$result = mysqli_query($conn, 'SELECT code FROM center WHERE id=' . $_POST['list']);
while ($row = mysqli_fetch_assoc($result))
{
echo $row['code'];
}
}
?>
</div>
</form>
Try to echo $row variables separately by concatenation.
So change this line
echo "<option value='$row[id]'>$row[name]</option>"
to
echo "<option value=". $row[id] .">".$row[name]."</option>"
or you can use escape character like this
echo "<option value={$row[id]}>{$row[name]}</option>"
I think now your select option would work.
If I understand you right, you're trying to do the same thing I was before I discovered this solution...
I was creating a dropdown for selecting how many results to show per page.
Total of 6 options, which I stored in an array...
$page_sizes = array(10, 25, 50, 100, 200, 500);
Next, I used a "foreach" to build the options list...and an if statement to show the option as selected ONLY if it matched the current page size (page size was determined earlier in the script using the $page_size variable)...
foreach($page_sizes as $pagesize_opt){
($pagesize_opt == $page_size) ? $pagesize_options .= '<option selected="selected" value="'.$pagesize_opt.'">'.$pagesize_opt.'</option>':
$pagesize_options .= '<option value="'.$pagesize_opt.'">'.$pagesize_opt.'</option>';
}
Then, I inserted my options into my drop down...
$page_size_select = '<strong>Results Per Page </strong><select id="analytics_page_size_select">'.$pagesize_options.'</select>';
You could do the same using a "while" iterator. Just check to see if the array element matches your selected element.
OR, if you want to get fancy and use an associative array which selects the option by the key instead of by the value, you can use the "key()" function to get the key and test whether it matches your selected key...
http://php.net/manual/en/function.key.php
So the entire code looks like this...
$page_sizes = array(10, 25, 50, 100, 200, 500);
foreach($page_sizes as $pagesize_opt){($pagesize_opt == $page_size) ? $pagesize_options .= '<option selected="selected" value="'.$pagesize_opt.'">'.$pagesize_opt.'</option>':
$pagesize_options .= '<option value="'.$pagesize_opt.'">'.$pagesize_opt.'</option>';
}
$page_size_select = 'Results Per Page '.$pagesize_options.'';
I am a newbie as far as JQuery, AJAX & PHP are concerned and I am trying to build a form with chained selects that will provide initial data for a new mysql record.
I have downloaded the JQuery chained select remote plugin and for the life of me I cannot figure out how to get the data returned for the second select dropdown. The first dropdown is populated using another function and when the user selects a value from this dropdown, I want that value to be used as the search string for the second dropdown.
The code snippet for the main form is:
<?php
<head>
<script type="text/javascript" src="../js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../js/jquery.chained.remote.js" charset="utf-8"></script>
</script>
<script type="text/javascript">
$('#series').remoteChained("#series", "../models/json.php");
</script>
</head>
<body>
<form action="" method="post">
<table border="1">
<tr>
<th>Season:</th>
<td><select name="season" id="mark">
<option value="">Select Season...</option>
<?php
$i = 0;
while ($i < count($showseason)){ // obtain seasons from getseason() function
?>
<option value="<?php echo $showseason[$i]; ?>">
<?php echo $showseason[$i]; ?> </option>
<?php
$i++;
} ?>
</select></td>
<th>Competition:</th><td><select name="competition" id="series">
<option value="">Competition type...</option>
</select></td>
The following is the code for the Mysql select (json.php)
<?php
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php';
include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/db_connect.php';
try
{
$result = $pdo->prepare("SELECT sideid, competition FROM pennantsides");
$result->execute();
echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
}
catch (PDOException $e)
{
$output = 'Error selecting records - Please contact your Site Administrator';
include $_SERVER['DOCUMENT_ROOT'] . '/views/output.html.php';
exit();
}
Isn't it $('#mark').remoteChained("#series", "../models/json.php"); you're trying to do ?
Also, what's the content of the json file when you launch it on your browser (or via whatever GET method you use) ?