use drop down menu to query mysql - php

Beginner here; I have searched many examples, still need some help.
I would like for the user to select an option from a dropdown box, and that option will query a table in mysql. I don't understand how to (in my html file) show the select statment in getprojectstatus.php.
<html>
<head>
<title>Status Dashboard</title>
</head>
<body style="background:#19245e url('images/fade.png')repeat-x;font-size:12px;font-family: Arial;line-height:18px;color:#FFFFFF;">
<script>
function displayProject(option)
{
var x;
if (option=='sciplay')
{
x="show Sciplay selected, show notes, status, etc..."
}
else if (option=='oklahoma')
{
x="show OK selected, show..."
}
else if (option=='northdakota')
{
x="show North Dakota selected, show..."
}
else if (option=='audit')
{
x="show Audit selected, show..."
}
else if (option=='sggaming')
{
x="show SG Gaming selected, show..."
}
else if (option=='all')
{
x="..."//(option=(1+2+3+4+5))
}
document.getElementById("demo").innerHTML=x;
}
</script>
<div align="center">
<TABLE BORDER="1">
<TR>
<TD><img src='images/header.png'/>
</TD>
</TR>
<TR>
<TD>
<TABLE BORDER="0" bgcolor="C0C0C0" align="left">
<TH>Projects
</TH>
<TR>
<TD>
<FORM action="getprojectstatus.php" method="post">
<SELECT onload="displayProject(this.value);" onchange="displayProject(this.value);">
<OPTION VALUE='all'>ALL</OPTION>
<OPTION VALUE='sciplay'>Sciplay</OPTION>
<OPTION VALUE='oklahoma'>Oklahoma</OPTION>
<OPTION VALUE='northdakota'>North Dakota</OPTION>
<OPTION VALUE='audit'>Audit SSAE16</OPTION>
<OPTION VALUE='sggaming'>SG Gaming</OPTION>
</SELECT>
</FORM>
</TD>
</TR>
</TABLE>
</TD>
</TR>
<TR>
<TD>
<p id="demo">
</p>
</TD>
</TR>
</TABLE>
</div>
</body>
and my getprojectstatus.php file:
<?php
//create connection variables
$host=`localhost`;
$user=`dashboard`;
$pw=`password`;
$db=`status`;
//create connection
$con=mysqli_connect("$host", "$user", "$pw", "$db");
//check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//take input from form and store as var queries
$option= $_POST['option'];
if ($option == 'sciplay')
{
$queries = "SELECT * FROM status where project=1"
}
else if ($option == 'oklahoma')
{
$queries = "SELECT * FROM status where project=2"
}
else if ($option == 'northdakota')
{
$queries = "SELECT * FROM status where project=3"
}
else if ($option == 'audit')
{
$queries = "SELECT * FROM status where project=4"
}
else if ($option == 'sggaming')
{
$queries = "SELECT * FROM status where project=5"
}
else ($option == 'all')
{
$queries = "SELECT * FROM status"
}
//store query as var result
$queries=$query;
$result=#mysqli_query($con,"$query");
//echo var result in table format
echo "<table border='1'>
<tr>
<th>Project</th>
<th>Subject</th>
<th>Status</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['project'] . "</td>";
echo "<td>" . $row['subject'] . "</td>";
echo "<td>" . $row['entry'] . "</td>";
echo "</tr>";
}
echo "</table>";
//close mysql connection
mysqli_close($con);
?>
Thanks for any help in advance!

OK, so it looks like you haven't fully grasped the client/server model employed in web based systems (we were all there at the beginning).
Here's a quick rundown, and then we'll talk about where you're issue lies.
You open a browser and type in a URL, hit enter
Your browser sends a request to the server that hosts the URL you entered
The server parses the request and loads up the specific file that was requested. For our purposes, that means running the PHP file to ultimately generate an HTML and javascript output
It sends this HTML (and javascript) to the browser. No executable PHP is ever sent to the browser, it all stays on the server.
Your browser receives this HTML (and javascript) and displays it.
Your browser can execute any javascript on the page, but if it needs information that is not already in your page source, it has to request it from the server. It can do this one of two ways: a) you can send a whole new request to the server, with the correct parameters such that the information you want is included up front or b) you can run an ajax request to pull the information you need, and then insert it into your page
So, at first glance it looks like the breakdown is occurring between step 5 and 6, you've loaded up a whole page in the browser, and it needs more information from the server but you're never actually sending that request to the server. If you were to send that request to the server (by either adding a submit button to your form, or adding a form submit request to your displayProject() function), then you've got no way (currently) to insert that new information into your existing page.
So, there's two potential answers to your problem:
If you want to understand better how to write a PHP application because you intend to do more of this in the future:
... then you should rewrite these two separate files as one single file. (I've dropped your code in pretty much as-is, I haven't done any checking for errors)
<?php
//create connection variables
$host=`localhost`;
$user=`dashboard`;
$pw=`password`;
$db=`status`;
//create connection
$con=mysqli_connect("$host", "$user", "$pw", "$db");
//check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//take input from form and store as var queries
$option= $_POST['option'];
if ($option == 'sciplay')
{
$queries = "SELECT * FROM status where project=1"
}
else if ($option == 'oklahoma')
{
$queries = "SELECT * FROM status where project=2"
}
else if ($option == 'northdakota')
{
$queries = "SELECT * FROM status where project=3"
}
else if ($option == 'audit')
{
$queries = "SELECT * FROM status where project=4"
}
else if ($option == 'sggaming')
{
$queries = "SELECT * FROM status where project=5"
}
else ($option == 'all')
{
$queries = "SELECT * FROM status"
}
//store query as var result
$queries=$query;
$result=#mysqli_query($con,"$query");
//The actual echo of the table display was moved to the area of the page it actually needs to go
//close mysql connection
mysqli_close($con);
?>
<html>
<head>
<title>Status Dashboard</title>
</head>
<body style="background:#19245e url('images/fade.png')repeat-x;font-size:12px;font-family: Arial;line-height:18px;color:#FFFFFF;">
<script>
function displayProject(option)
{
var x;
if (option=='sciplay')
{
x="show Sciplay selected, show notes, status, etc..."
}
else if (option=='oklahoma')
{
x="show OK selected, show..."
}
else if (option=='northdakota')
{
x="show North Dakota selected, show..."
}
else if (option=='audit')
{
x="show Audit selected, show..."
}
else if (option=='sggaming')
{
x="show SG Gaming selected, show..."
}
else if (option=='all')
{
x="..."//(option=(1+2+3+4+5))
}
document.getElementById("demo").innerHTML=x;
}
</script>
<div align="center">
<TABLE BORDER="1">
<TR>
<TD><img src='images/header.png'/>
</TD>
</TR>
<TR>
<TD>
<TABLE BORDER="0" bgcolor="C0C0C0" align="left">
<TH>Projects
</TH>
<TR>
<TD>
<!--
SOME CHANGES HERE: The form action is now pointing
to this same file, so that when you submit your form,
it goes back to this same file.
Also, I gave your select tag a "name" attribute so
that when you submit it, it'll actually be accessible
in the $_POST['option'] variable
-->
<FORM action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<SELECT name="option" onload="displayProject(this.value);" onchange="displayProject(this.value);">
<OPTION VALUE='all'>ALL</OPTION>
<OPTION VALUE='sciplay'>Sciplay</OPTION>
<OPTION VALUE='oklahoma'>Oklahoma</OPTION>
<OPTION VALUE='northdakota'>North Dakota</OPTION>
<OPTION VALUE='audit'>Audit SSAE16</OPTION>
<OPTION VALUE='sggaming'>SG Gaming</OPTION>
</SELECT>
<input type="submit" value="Reload Form">
</FORM>
</TD>
</TR>
</TABLE>
</TD>
</TR>
<TR>
<TD>
<!-- a <p> tag can't technically hold a <table> tag, but one thing at a time here -->
<p id="demo">
<?php
// I'm just lifting your structure out and placing it here for clarity purposes.
// really, you can just write these tags out in HTML directly,
// not go into PHP and echo them
echo "<table border='1'>
<tr>
<th>Project</th>
<th>Subject</th>
<th>Status</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['project'] . "</td>";
echo "<td>" . $row['subject'] . "</td>";
echo "<td>" . $row['entry'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</p>
</TD>
</TR>
</TABLE>
</div>
</body>
... so, what's going on here is that I've changed it up so that the data is being built and used, all in the same file. Your page now doesn't need to request new information, it's all right there, and if you want to change the form, then you submit and it requests the whole page again, now with the new information.
That's all well and good, but may not be exactly how you want your page to work. That said, you should understand how that process functions because any PHP application of even basic complexity will need to work in that way at least in part.
Now...
If you just want this page to function the way it appears you -want- it to function, i.e. you build your page, then request new information to update your page on form request:
... then we can get that done. Again, I haven't done any checking for errors. First things first, though, put this in your <head> tags:
<head>
<title>Status Dashboard</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
... we're going to be using jquery, just because in our case here, it let's us just worry about running the ajax request rather than bother setting up all of the necessary ins and outs. Then you want to add this to your displayProject function (just before the closing } ):
$.ajax({
url: 'getprojectstatus.php',
type: 'post',
data: 'option='+option,
success: function(data) {
$('#demo').html(data);
}
});
... all that's going on there is that you're sending your "option" selection to getprojectstatus.php, that file is generating your HTML output for your table, and then once it's received, it runs "success", which just inserts the data directly into the element with the "demo" id attribute. You should consider changing that to a <div>, at minimum, as the <p> might cause headaches.

I am not sure if I understand the problem correctly, but this might work for you:
<FORM action="getprojectstatus.php" method="post">
<SELECT onload="displayProject(this.value);" onchange="displayProject(this.value);">
<OPTION VALUE='none'>ALL</OPTION>
<OPTION VALUE='1'>Sciplay</OPTION>
<OPTION VALUE='2'>Oklahoma</OPTION>
<OPTION VALUE='3'>North Dakota</OPTION>
<OPTION VALUE='4'>Audit SSAE16</OPTION>
<OPTION VALUE='5'>SG Gaming</OPTION>
</SELECT>
</FORM>
And then in your PHP file:
$option= $_POST['option'];
$queries = "SELECT * FROM status"
if ($option != 'none'){
$queries = "SELECT * FROM status where project=".$option
}
I would also recommend researching some PHP Frameworks, maybe CodeIgniter and learning MVC patterns.

Related

filtering table by choosing in combobox

I need to get the list of diagnosed disease of the patient by choosing his name in the combo box, how can I do that? This is my code.
<select name="pname" class="textfields" id="model" style="width:180px;" onchange="getVal1();">
<option id="0" >--Select Patient Name--</option>
<?php
$con = mysqli_connect("localhost","root","","dbnpatient");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$pnum = $_GET['pnum'];
$query = mysqli_query($con, "SELECT * FROM tblnpatient");
while($row = mysqli_fetch_array($query)){
$pnum = $row['pnum'];
$pname = $row['pname'];
$addr = $row['addr'];
$complaints = $row['complaints'];
?>
<option id="<?php echo $pnum; ?>" data-pnum="<?php echo $pnum; ?>" data-addr="<?php echo $addr; ?>" data-complaints="<?php echo $complaints; ?>" value="<?php echo $pname; ?>"><?php echo $pname; ?></option>
<?php } ?>
This is my code for filtering the table: And i having a trouble in this code because nothings appear in the table when i select the pname
<?php
$con = mysqli_connect("localhost","root","","dbnpatient");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$pname = $_GET['pname'];
$result = mysqli_query($con,"SELECT * FROM tbldiagnosis WHERE pname='$pname'");
while($row = mysqli_fetch_array($result)) {
echo '<tr class="record">';
echo '<td>'.$row['diagnosis'].'</td>';
}
?>
This can be easily done using ajax. On change of the select, you can trigger a jQuery call to submit the selected value of the box to your PHP page, which has the MySQL to filter the table. The returned result will then be displayed on the page in the designated area.
Main Page:
<select name="pname">
<option value="pname-value">pname-value</option>
</select><br>
<div id="query_results"></div>
<script type="text/javascript">
$(document).ready(function() {
$('select[name="pname"]).on('change',function() {
var curPname=$(this).val();
$.ajax({
type:'GET',
url:'urltotable.php?pname='+curPname,
success:function(data) {
$("div#query_results").html(data);
}
});
});
});
</script>
This is a simplified ajax call that will grab the value from the select box named "pname" and it will send that value to the "url" variable in the ajax call via "GET". This page can then take that variable via GET and use it to get the query results. Upon successful completion, it will display the results inside the div we added with the ID of "query_results".
You can easily customize the select to use your current PHP as listed above, also.
Now for the "urltotable.php" as we specified above, you can use the table query you have above, but just be sure to add the GET line to it so that your pname variable is accessible to the script:
$pname=$_GET["pname"];
For more information about Ajax for full features list, click here to read about Ajax in the jQuery documentation.

Edit SQL with dropdown

So just like always, I'm working on code that up until now I have had no experience with.
What I'm trying to do is create a ticket type system for a department here at work to use to contact potential students. I'm ok with the HTML and PHP for the most part, it's learning the SQL that has me stumped. I'm really not even sure if it's all being done right. I may need to incorporate AJAX as well. Basically, the contact will fill out a form with information about what type of degree they want to pursue, and contact info etc... Everything inserts fine into the SQL but the problem comes when I want to edit it from my viewtable.php page.
This is just the working prototype, eventually it will have user login and other such things, as well as admin console, etc... so without further ado, here is my viewtable code. If it's insufficient, please let me know. I'll keep researching but any help you guys can offer would be appreciated.
<?php
session_start();
//Must be called before any code or white space is executed
/*
TODO:
1: Get checkboxes to load and display only what was posted via checkboxes from a previously loaded page
2: Cleanup
3: Hover messages for table headers
4: Program search bar
5: Get dropdown to do something
6: Program to only show 10 entries at a time, and be able to move to the next ten entries
7: program to be able to sort by "Last Name" , "First Name", etc...
8: Move database info to a called file for security and ease of access.
*/
$action=$_POST['action'];
$id=array($_POST['id']);
//Create Connection
$con = mysqli_connect("localhost","username","password","database");
//Check Connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
//echo "Connection Successful! \n";
}
//If the action dropdown was set
if($action = 'delete') {
for($i=0;$i<$count;$i++){
$del_id = $checkbox[$i];
$sql ="DELETE FROM persons WHERE PID='$del_id'";
$result = mysql_query($sql);}
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete_multiple.php\">";}
}
$query = "Select * FROM persons";
$result = mysqli_query($con, $query);
$num=mysqli_num_rows($result);
echo $id;
echo $action;
?>
<!DOCTYPE html>
<html>
<head>
<style>
tr:nth-child(even) {
background-color:#00fff0;
}
</style>
<script>
</script>
</head>
<body>
<table id="persons" name="persons" border="0" cellpadding="1">
<form name="database" action="viewtable.php" type="post">
<div type="hidden" class="pidmessage" style="display:none;">Unique Identifier</div>
<div type="hidden" class="fnamemessage" style="display:none;">Contact's First Name</div>
<div type="hidden" class="lnamemessage" style="display:none;">Contact's Last Name</div>
<div type="hidden" class="emailmessage" style="display:none;">Contact's Email Address</div>
<div type="hidden" class="phonemessage" style="display:none;">Contact's Home Phone Number</div>
<div type="hidden" class="cellmessage" style="display:none;">Contact's Mobile Phone Number</div>
<div type="hidden" class="campusmessage" style="display:none;">Is the contact interested in residential or online courses?</div>
<div type="hidden" class="statemessage" style="display:none;">Contact's Home State</div>
<div type="hidden" class="studenttypemessage" style="display:none;">The contact is interested in enrolling as this</div>
<div type="hidden" class="termmessage" style="display:none;">The contact is interested in enrolling beginning this term</div>
<div type="hidden" class="enrollmentmessage" style="display:none;">The contact is interested in enrolling in this many credit hours</div>
<div type="hidden" class="degreemessage" style="display:none;">The contact is interested in pursuing this type of degree</div>
<div type="hidden" class="messagemessage" style="display:none;">The contact heard about TTU in this manner</div>
<div type="hidden" class="commentsmessage" style="display:none;">These are comments the contact left</div>
<?php
$i = 0;
$data = array();
while($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
$colNames = array_keys(reset($data));
?>
<tr><th> </th>
<?php
foreach($colNames as $colName)
{
echo"<th class='{$colName}'>$colName</th>";
}
?>
</tr>
<?php
foreach($data as $row)
{
echo "<tr>";
echo "<td><input type='checkbox' name='checkbox[]' value='{$row['PID']}'></input></td>";
foreach($colNames as $colName)
{
echo "<td>".$row[$colName]."</td>";
}
echo"</tr>";
}
?>
<tr class="clear"><td> </td><td colspan="7">
<select name="action">
<option value="">--Select One--</option>
<option value="delete">Delete Entry</option>
<option value="assign">Assign</option>
<option value="contacted">Move to contacted</option>
<option value="edit">Edit</option>
<option value="">Cancel</option>
</select></td>
<td colspan="7">
<input type="submit" name="submit" value="Submit"> </input></td></tr>
</form>
</table>
</body>
</html>
<?php
mysqli_close($con);
?>
Note: The todo list that is commented out on top is on the list of things (clearly) todo...
So far from what I see its this section:
for($i=0;$i<$count;$i++){
$del_id = $checkbox[$i];
$sql ="DELETE FROM persons WHERE PID='$del_id'";
$result = mysql_query($sql);}
I don't see where $count is declared, nor $checkbox. If $checkbox is an array, where are you getting it from?
Otherwise, making this work from ajax shouldn't be to hard as long as you're familiar with jQuery. Just cut the code that does the updating to its own php file, and have jQuery pass the form values through ajax to the new script.

Display result in dropdown and select to perform query in php mysql

I have a database named Data which has a table in which their are different names of products their id and prices, i want to make a web page using php so that i can edit,add and save the items from the web page to the DB and search the names accordingly.
<html>
<head>
<title>Products store</title>
</head>
<body>
<p style="font-size:20px" align="center"> <b>Product Database Editor</b> </p>
<p>
<form method="post">
Enter Product Name: <input type="text" name="pname" id="pname" size="70">
<input type="submit">
</p>
<form method="post">
<select id="opt" name="opt">
<?php
$pname = $_REQUEST['pname'];
// $pname= mysql_real_escape_string($_POST['pname']);
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Dataentry", $con);
$result = mysql_query("SELECT * FROM products where name like '%$pname%'");
$result_rows = mysql_num_rows($result);
if($pname==NULL)
{
echo "Please enter a product name!";
}
else if($result_rows==0)
{
echo "Product Name does not exist!";
}
else
{
while($row = mysql_fetch_array($result))
{
$name = $row['name'];
echo "<option value='$name_selected'>$name</option>";
//echo ("<option value = '" . $row['name'] . "'>" . $row['id'] . "</option>");
echo $name_selected;
echo "<br />";
}
}
mysql_close($con);
?>
</select>
</form>
</body>
</html>
when i run this code i get the names list in the dropdown but after i select any name, nothing happens, how should i modify my code so that i can select any name from the dropdown and then be able to fetch the price of that particular name to edit it.
please help, coding will be much helpful.
Suppose you have a question like this in your dropdown menu.
Q - How many colors does the US flag has?
Now, from what I understand you want your choice from the drop down menu to appear instantly..
Well, here is a simple select form.
<form method="post">
<select id="opt" name="opt">
<option value="four">four</option>
<option value="five">five</option>
<option value="two">two</option>
<option value="million">million</option>
</select>​
And, the JS code:
$(document).ready(function() {
$("#opt").change(function() {
alert($(this).val());
});
});​
Now, click her a DEMO with jsFiddle to show you, how it works.
You can copy/paste the codes and include them in your site, this is a simple code, but you if you small knowledge of Javascript you can manipulate the data the way you need it to appear. .
To get a value of an input (this case, from a dropdown) on the fly, you need to use client-side scripting language javascript (or jquery) and use ajax to sent it to server-side, where the code is in PHP.

Combobox that list items based in the selected item in another combobox

I do have a routine that uses PHP, MySQL and JavaScript. There are two tables: tbl_category and tbl_subcategory just like this:
tbl_category
cat_id
cat_name
tbl_subcategory
scat_id
cat_parent_id
cat_name
They have some information inside like
tbl_category:
Pants
Shoes
t-Shirts
tbl_subcategory:
1 Jeans
1 Heavy Duty
2 Boots
2 Sandals
3 Long Sleeves
3 Short Sleeves
3 Polo
I put in the file head the link to the javascript library:
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
of course I download previously from the jquery website(newer version).
I have now the script routine:
<script type="text/javascript">
$(document).ready(function(){
$("select[name=cat_id").change(function(){
$("select[name=scat_id]").html('<option value="">Loading...</option>');
$.post("ajax_subcategory.php",
{cat_id:$(this).val()},
function(valor){
$("select[name=scat_id]").html(valor);
}
)
})
})
Now I have the form, with the select field Category pre-loaded with data from the table tbl_category:
<form name="form" method="post" action="" enctype="multipart/form-data">
<table width="100%" border="0" cellspacing="6" cellpadding="0">
<tr>
<td align="right">Category:</td>
<td><select name="cat_id" >
<option value="0">Choose category</option>
<?php
$sql1 =mysql_query("SELECT * FROM tbl_category ORDER by cat_name")or die(mysql_error());
while($row = mysql_fetch_array($sql1))
{
echo ("<option value=\"$row[cat_id]\"" . ($sql1 == $row["cat_name"] ? " selected" : "") . ">$row[cat_name]</option>");
}
?></select>
</td>
</tr>
<tr>
<td align="right">Sub-category:</td>
<td><select name="scat_id" selected="selected" >
<option value="0">Waiting category...</option>
</select>
</td>
</tr>
</table>
<input type="submit" name="submit" value="Submit"/>
</form>
and then the php file called ajax_subcategory:
<?php
include "../connect_to_mysql.php";
$cat_id = $_POST['cat_id'];
$sql1 =mysql_query("SELECT * FROM tbl_subcategory WHERE cat_parent_id='$cat_id' ORDER by cat_name")or die(mysql_error());
while($row = mysql_fetch_array($sql1))
{
echo ("<option value=\"$row[scat_id]\"" . ($sql1 == $row["scat_name"] ? " selected" : "") . ">$row[scat_name]</option>");
}
?>
Done! Everything looks perfect and beautiful. When I select the item in the first combo I can see the Javascript in action and the Loading... showing up but the the second ComboBox always is empty
don't matter what item I select it shows up empty and become smaller(width).
This is a good routine and I saw working in the web from another website.
Can you guys help me out to find a solution?
Thanks
First of all, you need to follow step by step troubleshooting to analyze the data. This is what I would do, in your case:
Examine the cat_id before posting:
$("select[name=cat_id").change(function(){
alert($(this).val());
Print the string inside your mysql_query (ajax_subcategory page) as it is, and examine if the query is valid. Try this query directly in MySQL console or phpMyAdmin and examine its output.
Analyze the ajax response: Use FireBug or the Network tab in Chrome and check the Ajax response. Sometimes, there will be some PHP warnings or notices generated by your ajax_subcategory page.
Note: I do not understand why you check the condition $sql1 == $row["cat_name"]. $sql1 will be a resource Id, and according to your query, $row['cat_name'] is a string representing your sub category name.
As an aside, mysql_* functions are deprecated and their use strongly discouraged. Use mysqli_* functions or PDO.
Please change $row["scat_name"] to $row["cat_name"]
<?php
include "../connect_to_mysql.php";
$cat_id = $_POST['cat_id'];
$sql1 =mysql_query("SELECT * FROM tbl_subcategory WHERE cat_parent_id='$cat_id' ORDER by cat_name")or die(mysql_error());
while($row = mysql_fetch_array($sql1))
{
echo ("<option value=\"$row[scat_id]\"" . ($sql1 == $row["cat_name"] ? " selected" : "") . ">$row[cat_name]</option>");
}
?>

Dropdown List Value From SQL in PHP

I want to do this function in php. i have two fields, one is text box and an
other one is drop down list. Drop down list contains values from sql. When one of the value is selected from the drop down list i want the text box to be filled according to the option which is selected.
Following is the drop down list code,
<td>Test Group ID</td>
<td><select id="testgroupid" name="testgroupid" style="column-width:35">
<option value="<?php echo $testgroupid;?>"><?php echo $testgroupid;?></option>
<?php
$x=new con();
$x->connect();
$retval = "select distinct(Id) from testgroupmaster";
$sql1 = mysql_query($retval) or die (mysql_error());
while($res=mysql_fetch_array($sql1, MYSQL_BOTH)){
?>
<option value="<?=$res['Id'];?>"><?=$res['Id'];?></option>
<?
}
?>
</select></td>
According to the id,I want textbox to be filled, How can i do this ? Pls help friends.
<tr>
<td>Test Group Name</td>
<td><input type="text" name="testgroupname" id="zipsearch" value="<?php echo $testgroupname; ?> "></td>
</tr>
If you want your textbox to be filled immediately after the dropdown selection changes, the simplest way is to use javascript:
<td><select id="testgroupid" name="testgroupid" style="column-width:35"
onchange='document.getElementsByName("testgroupname")[0].value =
document.getElementById("testgroupid").options[e.selectedIndex].value;'>
You need JavaScript for that. Use jQuery (or your favorite library) and bind an event listener to the combobox.
Example with jQuery:
$("#myCombo").change(function(e){
$("myTextField").val( $("#myCombo").val() );
});
I have one suggestion which involves jQuery. I do not know if you are using this library, but I am posting it anyway :)
<script type="text/javascript">
$(function() {
$("#testgroupid").change(function{
$("#zipsearch").text($(this option:selected).val();
});
});
</script>
On change event on the dropbown-box, this function fires, and sets the zipsearch-input accordingly.
I am not sure where $testgroupname comes from but I take it you would like to get that value upon selection in the dropdown. If you don´t have the value available on the client you have to retrieve it from the server somehow.
You can´t use PHP to fill the text box since you do not send your posts when an options is selected in the dropdown. There are many alternatives on how to solve this. I would personally use Ajax to fill the textbox without posting to server.
Good place to start:
http://buffernow.com/2012/08/cascading-dropdown-ajax/
html
<select id="testgroupid" name="testgroupid"
style="column-width:35" onChange=filltext();>
javascript
function filltext()
{
var e = document.getElementById("testgroupid");
var group = e.options[e.selectedIndex].text;
document.getElementById("zipsearch").value= group ;
}
your php code is wrong here
<option value="<?=$res['Id'];?>"><?=`$res['Id']`;?></option>
change to
<option value="<?=$res['Id'];?>"><?=$res['GROUP_NAME'];?></option>
Try like this
<script>
function selecteditem(selectedval)
{
jQuery.post("<?php echo JURI::root().'test.php'?>", { id: selectedval },
function(data) {
jQuery('.zipsearch').val(data);
});
}
</script>
//test.php on the root
<?php
$val=$_POST['id'];
//do what you want with $val
//and say final output is in variable $result than echo it
echo $result;
?>
<!--html code here-->
<select id="testgroupid" name="testgroupid" style="column-width:35" onclick="selecteditem(this.value);">
<option value="<?php echo $testgroupid;?>"><?php echo $testgroupid;?></option>
<?php
$x=new con();
$x->connect();
$retval = "select distinct(Id) from testgroupmaster";
$sql1 = mysql_query($retval) or die (mysql_error());
while($res=mysql_fetch_array($sql1, MYSQL_BOTH))
{
?>
<option value="<?=$res['Id'];?>"><?=$res['Id'];?></option>
<?
}
?>
</select>
<input type="text" name="testgroupname" id="zipsearch" class="zipsearch" value="<?php echo $testgroupname; ?> ">
<?php
// Assume $db is a PDO object
$dbh = new PDO('mysql:host=localhost;dbname=populatedropdown', "root", "");
$query = $dbh->query("select * from position"); // Run your query
echo '<form action="populate.php" method="get" name="send3">';
echo '<select name="populate">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo '</select>';// Close your drop down box
echo '</form>';
?>
<script language="JavaScript">
function send_input1(){
document.send1.input4.value = document.send3.populate.value;
}
</script>
<form name="send1" action=javascript:send_input1()>
<p><input type=submit value=Enter>
</p><input size=30 name="input4">
</form>

Categories