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.'';
Related
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.
I am building an html form that will need to dynamically fill in the first input field with the "facility" column values in my "doctors" table. The facility column contains the names of our 7 offices. However, when I run the code below, my input field is blank and I have verified there is data in my "doctors" table. After this is working, I need to be able to dynamically fill in the second input field (which I haven't coded for in the code below because I'm stuck with the issue of first input) with the "provider" column values, also from my "doctors" table. The "provider" column contains all the provider names in our practice. However, the providers should be filtered, so that only the providers at the facility from the first input field is showing.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<?php
$link = mysqli_connect("localhost","USERNAME","PASSWORD");
mysqli_select_db($link,"DB");
?>
<head>
<title> Untitled Doc</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form name "form1" action="" method="post">
<select>
<?php
$res=mysqli_query($link,"select facility from doctors");
while($row=mysqli_fetch_array($res)){?>
<option> <?php echo $row ["facility"]; ?></option>
<?php }?>
</select>
</form>
</body>
</html>
It is important that you check if the connection have been established, as I have copied your code as it is and use it on my side and was working fine, therefore made me suspect that the problem might be connection related. also check how sensitive your server is maybe your server see this as an error : $row ["facility"] that space might be the problem as well, but it didn't on my side.
Check your server error log and also enable error reporting at the top of your page add
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);?>
That will enable error reporting, but use that on local server only
Then on live site send them to error log
error_reporting(E_ALL);
ini_set('display_errors',0);
ini_set('log_errors',1);
also to get the mysqli errors, before your connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Important to check if your query does indeed return results before trying to display them.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<?php
$link = mysqli_connect("localhost", "root", "", "DB");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
<head>
<title> Untitled Doc</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form name ="form1" action="" method="post">
<?php
$query = "SELECT facility FROM doctors";
if ($res = mysqli_query($link, $query)) {
echo "<select name=\"myselect\">";
while ($row = mysqli_fetch_assoc($res)) {
?>
<option value="<?php echo $row['facility'];?>"><?php echo $row['facility'];?></option>
<?php
}
echo "</select>";
mysqli_free_result($res);
} else {
printf("Error : %s\n", mysqli_error($link));
}
/* close connection */
mysqli_close($link);
?>
</form>
</body>
</html>
NB: For your own benefit, if you haven't used prepared statements, would suggest that you learn them as well, though they are not needed
in this case
When doing this kinda of query its important to catch errors so that you can debug easier. I have added a different way of connecting using mysqli object. Try this, this should determine if you have a connection error or if your query is not returning any results
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<?php
$link = new mysqli("localhost","USERNAME","PASSWORD", "DBNAME");
// Check connection
if ($link->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<head>
<title> Untitled Doc</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form name "form1" action="" method="post">
<select>
<?php
$res = $link->query("select facility from doctors");
// Check to see if query returned results
if($res->num_rows > 0 {
while($row = $res->fetch_assoc())
{
echo '<option>' . $row["facility"] . '</option>';
}
} else {
echo 'No results';
}
?>
</select>
</form>
</body>
</html>
Based on your code, when you want to access the data in a array you should put no space between the variable and the square brackets [] or your application will not show anything. In your code when you want to echo use
<option><?php echo $row["facility"]; ?></option>
instead of
<option><?php echo $row ["facility"]; ?></option>
For another case of the second field depends on the first field, i suggest to use JavaScript to get the data by sending the first data because it will reduce the processed of getting the data.
UPDATED:
To access your data, please add another parameter in your mysqli_fetch_array to be like this
while($row = mysqli_fetch_array($res, MYSQLI_ASSOC))
this will make your data can be access using name on your table
<select>
<?php
$res=mysqli_query($link,"select facility from doctors");
while($row = $result->fetch_assoc($res))
{
?>
<option> <?php echo $row ["facility"]; ?></option>
<?php
}
?>
</select>
i am creating three drop down menu and it work very good but i want that the second drop list appear on the selection of the first one and the third on the selection of the second one how to do that if any one can guide me or give me an example i will appreciate that
PS: the second drop list or table have a foreign key from the first one so here i want to work to populate the second based on the selection of the first.
fun.inc.php
<?php
require_once('db.inc.php');
function connect(){
mysql_connect(DB_Host, DB_User ,DB_Pass )or die("could not connect to the database" .mysql_error());
mysql_select_db(DB_Name)or die("could not select database");
}
function close(){
mysql_close();
}
function countryQuery(){
$countryData = mysql_query("SELECT * FROM country");
while($record = mysql_fetch_array($countryData)){
echo'<option value="' . $record['country_name'] . '">' . $record['country_name'] . '</option>';
}
}
function specializationQuery(){
$specData = mysql_query("SELECT * FROM specialization");
while($recordJob = mysql_fetch_array($specData)){
echo'<option value="' . $recordJob['specialization_name'] . '">' . $recordJob['specialization_name'] . '</option>';
}
}
function governorateQuery(){
$goverData = mysql_query("SELECT * FROM governorate");
while($recordGover = mysql_fetch_array($goverData)){
echo'<option value="' . $recordGover['governorate_name'] . '">' . $recordGover['governorate_name'] . '</option>';
}
}
?>
index.php
<?php
require_once('func.inc.php');
connect();
?>
<!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>testDroplistdown</title>
</head>
<body>
<p align="center">
<select name="dropdown">
<?php countryQuery(); ?>
</select>
</p>
<br />
<br />
<p align="center">
<select name="dropdown2">
<?php governorateQuery(); ?>
</select>
</p>
<p align="left">
<select name="dropdown3">
<?php specializationQuery(); ?>
</select>
<?php close(); ?>
</p>
</body>
</html>
make sure u never leave a after your php closing tag and the begging of your html header, it can trow some nasty errors
this script should work
<?php
require_once('func.inc.php');
connect();
?>
<!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>testDroplistdown</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p align="center">
<div id="dropdown1div"><select id="dropdown1" name="dropdown">
<?php countryQuery(); ?>
</select></div>
</p>
<br />
<br />
<p align="center">
<div id="dropdown2div"></div>
</p>
<p align="left">
<div id="dropdown3div"></div>
<script type="text/javascript">
$("#dropdown").change(function() {
val = $(this).val();
var html = $.ajax({
url: "dropdown_select.php?dropdown=2&val="+val+"",
async: true,
success: function(data) {
$('#dropdown2div').html(data);
}////////////function html////////
})/////////function ajax//////////
});
</script>
<?php close(); ?>
</p>
</body>
</html>
dropdown_select.php
<?php
require_once('func.inc.php');
connect();
if(isset($_GET['val'])){
$val = $_GET['val'];
$dropdown = $_GET['dropdown'];
}
if($dropdown == '2'){
echo '<select id="dropdown2" name="dropdown2">';
governorateQuery();
echo '</select>';
?>
<script type="text/javascript">
$("#dropdown2").change(function() {
val = $(this).val();
var html = $.ajax({
url: "dropdown_select.php?dropdown=3&val="+val+"",
async: true,
success: function(data) {
$('#dropdown3div').html(data);
}////////////function html////////
})/////////function ajax//////////
});
</script>
} // end if statement
if($dropdown == '3'){
echo '<select id="dropdown3" name="dropdown3">';
specializationQuery();
echo '</select>';
} // end if statement
close();
?>
You can't do that with PHP only, you need to use AJAX.
Ajax is a technique using javascript and PHP to load new results according to user input.
Let's say you select a country and you get a new select box with all the cities FROM that country.
You'll have to create an event handler to the first select box:
<select name="dropdown" onchange="loadNewSelectBox(this.value)">
// values
</select>
The loadNewSelectBox would be an function that would post a new xmlhttp request to a php file on your server with the value of your select box. Then you would echo data from that PHP file (json, xml, html..) with response. Your response (for beginner) would probably be html containing the new select box. Then you would append that response to a div or paragraph.
This is an example similar to your task : http://www.w3schools.com/php/php_ajax_database.asp
And this is a good learning source.
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
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
I am having a bit of trouble. It does not seem to be a big deal, but I have created a page that the user can edit a MySQL database. Once they click submit it should process the php within the if statement and echo 1 record updated. The problem is that it does not wait to echo the statement. It just seems to ignore the way I wrote my if and display the whole page. Can anyone see where I went wrong.
<!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></title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php require("serverInfo.php"); ?>
<?php
$res = mysql_query("SELECT * FROM cardLists order by cardID") or die(mysql_error());
echo "<select name = 'Cards'>";
while($row=mysql_fetch_assoc($res)) {
echo "<option value=\"$row[cardID]\">$row[cardID]</option>";
}
echo "</select>";
?>
Amount to Add: <input type="text" name="Add" />
<input type="submit" />
</form>
<?php
if(isset($_POST['submit']));
{
require("serverInfo.php");
mysql_query("UPDATE `cardLists` SET `AmountLeft` = `AmountLeft` + ".mysql_real_escape_string($_POST['Add'])." WHERE `cardID` = '".mysql_real_escape_string($_POST['Cards'])."'");
mysql_close($link);
echo "1 record Updated";
}
?>
<br />
<input type="submit" name="main" id="main" value="Return To Main" />
</body>
</html>
if(isset($_POST['submit']));
1) Should not have a semicolon after it.
2) $_POST['submit'] is not set. You have to set a name on your submit button and give it a value. Just setting the type to 'submit' does not return a value for $_POST['submit'] in PHP.
You've got a ; after your if statement.
I noticed that you have two submit buttons and I assume that you are using the first one.
Try giving it a name="submit" and a value too.
Of course it doesnt. PHP runs in the server side, not in browser!
Open your page source. There is no PHP. Nothing to wait.
You need another page to send your form to.
And it is a big deal. It's a cornestone of understanding how the web does work.