Select dropdown value to get a populated data from database mysql - php

I have a populated dropdown list from mysql on one page.
What code should i write in php so that on selection of dropdown list's value, a new page is opened and data is fetched from mysql, provided i have required fields in database.
<form name="form1">
<select>
<?php
$con=mysql_connect("localhost","FreeUser","123456");
if(!$con)
{
die('Connection failed' . mysql_error());
}
mysql_select_db("human_resource", $con);
$sql1=mysql_query("SELECT eid_emp,name_emp FROM employee_details");
while ($data=mysql_fetch_assoc($sql1))
{
?>
<option name="drop1" checked value ="<?php echo $data['eid_emp'] ?>" >
<?php echo $data['name_emp']; ?>
</option>
<?php
}
mysql_close($con);
?>
</select>
</form>

The answer is there is no PHP code to do what you're asking.
You'll need two things: 1). Some javascript to hook into your form and 2). a way to render the resulting query.
here is some javascript to hook into the form, assuming jquery for brevity (although you should just give the select an ID or a class, which would make the selector less obnoxious):
$('form[name="form1"] select').change(function(){
location.href='renderer.php?dataKey=' + $(this).val();
});
From there, you'll navigate to renderer.php along with $_GET value for dataKey. render it as your will. If you want to open a new window, use a window.open call instead of setting location.href.

has nothing to do with php or mysql ... you could add an "onchange" handler to your < select > element ...
<select onchange="javascript:someFunctionCallHere()">
a call to your forms submit() method should be what you want...

Not a lot of information, but you could do something like this:
<form name="form1" method="POST" action="page.php">
<select onchange="form1.submit()">
Then in the head of your page
<?php
if(count($_POST))
{
// do stuff
header( 'Location: http://somesite.com' ) ;

Related

data fetched from database but id of this this table item not showing

Hi i have update my question to explain you my problem easily.Okay so,
What i wnant and whats wrong with me?
i code a product form where i require getcatlist.php which help me get value from sql database and show in product page, Snapshot of product form product form image
Product form code
<section class="main-section">
<article class="prod-item">
<h3>Product Form</h3>
<form action="addproducts.php" method="get" name="product_form">
<section class="select-box">
<label for="category">Category</label>
<?php require_once("getcatlist.php"); ?>
<input type="hidden" name="cat_id" value="<?php echo $_GET['cat_id']; ?>" >
</section>
</form>
</article>
</section>
my javascript in product form page used to create query string code
<script type="text/javascript">
function showCategory(str)
{
document.product_form.action="addproducts.php?cat_id="+str;
}
</script>
**getcallist.php page code which fetch data from databse and show in select tag **
<?php
error_reporting(E_ALL ^ E_NOTICE);
require_once("../data_connect.php");
$error_msg = "";
$cat_id = "";
$catsql = "SELECT Cat_id,CategoryName FROM category order by Cat_id asc; ";
$cat_query = mysqli_query($connect,$catsql);
$numrows = mysqli_num_rows($cat_query);
$cat_id = $_GET['cat_id'];
if($numrows == 0)
{
$error_msg= "No Categories Found";
}
else{
echo "<select name=\"category\" id=\"category\" onchange=\"showCategory(this.value)\" >";
echo "<option value=\"null\">Select your category</option>";
while($catrow = mysqli_fetch_assoc($cat_query))
{
if ($catrow['Cat_id'] == $cat_id){
echo "<option value=\"".$catrow['Cat_id']."\" selected=\"selected\">".$catrow['CategoryName']."</option>";
}
else{
echo "<option value=\"".$catrow['Cat_id']."\">".$catrow['CategoryName']."</option>";
}
}
echo "</select>";
}
?>
here is my ajax code which move to another page when i click on dropdown list
<script type="text/javascript">
/**/$(document).ready(function(){
$("#category").change(function(){
var code = $(this).val();
if(code == 1)
{
$('.main-section').load('addconsoles.php');
}
else if(code == 2)
{
$('.main-section').load('addaccessories.php');
}
else if(code == 3)
{
$('.main-section').load('addgames.php');
}
});
});
</script>
okay i wants to create a query string of category list, when i click on any category option in dropdown list it wont show me any thing in url. This is the big problem i face and also when i try to set and get value in php oop class(require in product form page) it won't set and get when echo it.
Please help me out from this problem, Thanks
I think you have somewhat mis-understood how HTML forms work.
The code you've got will not work as you expect because you have got the cat_id field defined twice within your form - once in the hidden field you created, and again when you alter the action method of the form via the JavaScript. However when your JavaScript runs, it modifies the "action" string, but the hidden field will not change, and when you submit the form, the browser will submit the value from the hidden field, and ignores the value you manually added to the "action" method. This is just the default behaviour in such a situation, in order to resolve the ambiguity you created.
Therefore if at the time the page was first loaded, there was no value in cat_id (which seems likely, looking at your code), then no value for cat_id will be sent to the server when the form is submitted.
However, all of the code I described above is actually unnecessary. You can directly use the value of the dropdownlist as the cat_id. Simply changing the "name" parameter of your <select>, as follows:
echo '<select name="cat_id" id="category">';
will make the cat_id parameter change to whatever is in the selected value of the dropdown when the form is submitted.
You do not need the "showCategory" function, or the hidden field.
So the form can be
<form action="addproducts.php" method="get" name="product_form">
<section class="select-box">
<label for="category">Category</label>
<?php require_once("getcatlist.php"); ?>
</section>
</form>
without the hidden field, and the "showCategory" JavaScript function can be deleted entirely.
N.B. From this code it seems you have no way to submit this "addproducts" form to the server. It's not clear whether you have some other JavaScript elsewhere which controls this and is triggered based on some other event, and/or whether you need to add a "submit" button to the form. Either way, nothing will be sent to the server until you cause the form to be submitted, or provide a way for the user to cause it.
I hope this is useful, please comment if you still find anything unclear.

check if checkbox is checked in php

I have a check box list which I fill it with data from my table.Here is the code:
<?php
mysql_connect("localhost","root","");
mysql_select_db("erp");
$a="Select * from magazine";
$b=mysql_query($a);
$c=mysql_fetch_array($b);
while($c=mysql_fetch_array($b))
{
print '<input type="checkbox"/>'.$c['den_mag'];
echo "</br>";
}
if(isset($_POST['den_mag']))
{
echo "aaaa";
}
?>
It's a simple query and for each data just show it with a checkbox.Now what I want is when I press a checkbox the value of that checkbox to be shown in a table.So if I have check1 with value a , check2 with value b and I check check1 the value a to be outputted to a table row.How can I achieve that? how cand I get which checkbox is checked?
A few notes:
Try to avoid using SELECT * queries. Select the fields you are going to use:
$sql= '
SELECT
id,
den_mag
FROM
magazine
';
Use better variable names. $a and $c make your code harder to follow for others, and for yourself when you come back at a later time. Use more descriptive variable names like $query_object and $row. Your code should read almost like an essay describing what you're doing.
In your form, use an array of elements. By giving the input a name like selected_magazines[], you will end up with an array in your post data, which is what you want -- multiple selections
Use the row ID as the value of the checkbox element. Your array in POST will then be a list of all the IDs that the user selected
Separate your logic from your HTML generation. The top portion of your script should take care of all logic and decisions. At the bottom, output your HTML and avoid making logical decisions. It makes for a script that is easier to follow and maintain, as well as debug.
Here is a sample script incorporating these ideas with the details you've given:
<?php
// FILE: myfile.php
mysql_connect("localhost","root","");
mysql_select_db("erp");
if(isset($_POST['selected_magazine'])) {
// $_POST['selected_magazine'] will contain selected IDs
print 'You selected: ';
print '<ul><li>'.implode($_POST['selected_magazine'], '</li><li>').'</li></ul>';
die();
}
$sql= '
SELECT
`id`,
`den_mag`
FROM
`magazine`
';
$query_object=mysql_query($sql);
$checkboxes = array();
while($row = mysql_fetch_array($query_object)) {
$checkboxes[] = '<input name="selected_magazine[]" value="'.$row['id'].'" type="checkbox" /> '.$row['den_mag'];
}
?>
<form action="myfile.php" method="post">
<?php print implode('<br>', $checkboxes); ?>
<input type="submit" value="Submit" />
</form>
<input name="test" type="checkbox" />
<?php
if(isset($_REQUEST['test'])){
// selected
}
?>
When you give input-type elements (input, textarea, select, button) a name attribute (like I did), the browser will submit the state/value of the element to the server (if the containing form has been submitted).
In case of checkboxes, you don't really need to check the value, but just that it exists. If the checkbox is not selected, it won't be set.
Also, you need to understand the client-server flow. PHP can't check for something if the client does not send it.
And finally, someone mentioned jQuery. jQuery is plain javascript with perhaps some added sugar. But the point is, you could in theory change stuff with jQuery so that it gets (or doesn't get) submitted with the request. For example, you could get jQuery to destroy the checkbox before the form is submitted (the checkbox won't be sent in this case).
Here you go :
<html>
<input name="test" value="true" type="checkbox" />
</html>
<?php
$Checkbox1 = "{$_POST['test']}";
if($Checkbox1 == 'true'){
// yes, it is checked
}
?>

Extract value from select/option tag in php?

I am not exactly how to do it and how to word the question, so i shall try my best (PS: i'm new to web dev, so please be clear in your answers if you could).
So, I have got a drop down menu with the list names, which are taken from my database. In that database i have a table with names column (the ones that are rendered to the dropdown box) and relevant information to those names. Now, I want that relevant information to appear below in a tag when a user choose one of those names. I also cannot use the form.submit() method because my submit button is already taken for something else.
Here is the code to that bit:
<form name="name_choice" method="post" action="index.php">
<select name="names" onchange="form.some_method()">
<option value="NULL" selected="selected">--Select name--</option>
<?php
for ( $i = 0; $i < $numrows; $i++ ) { //for all the columns, iterate and print out
$id_names = mysql_result($result, $i);
echo "<option value='".$id_names."'>".$id_names."</option>";
}
?>
</select>
</form>
So the bit above works fine, but the "some_method()" is my problem, i don't know what to trigger to display the text in the div below the drop down box (code is below for it):
<div class="information"> <!--if the name is chosen ONLY!-->
<?php
if($_POST['names'] == "NULL") {
echo '<p>Please select an option from the select box.</p>'; //this bit is for testing
}
else {
echo '<p>You have selected: <strong>', $_POST['names'], '</strong>.</p>';
//and then how to echo the relevant information?:(
}
?>
</div><!--end of possible info-->
onchange is a JavaScript event. PHP can't do realtime processing of form data, as it sits on the server and the form is on the client. You can sort of do it by using AJAX and passing the form data as the user types, but that would be a lot more work than is needed. Take a look at JavaScript form validation posts to get yourself headed on the correct path.

Two drop down list values auto selected based on php session value

I have two drop down lists.
Second one is populated based on value chosen in the first one. I'm using Double Combo Script Credit By JavaScript Kit to do that (I am very bad with javascript).
I use this to filter results from my Mysql database.
The problem is that when user applies filter i want him to see what he applied (when page refreshes or user goes to other page) - those values should be seen as selected in both drop down lists. I can't figure out where i should place an event or something else.
I'm holding subcategory values from the second drop down list in php session :
if (isset($_SESSION['subcat']) && !isset($_GET['subcat'])){
$color= $_SESSION['subcat'];
}
elseif (!isset($_SESSION['subcat']) && isset($_GET['subcat']))
{
$_SESSION['subcat'] = mysql_real_escape_string($_GET['subcat']);
$color= $_SESSION['subcat'];
}
elseif (isset($_SESSION['subcat']) && isset($_GET['subcat'])){
unset($_SESSION['subcat']);
$_SESSION['subcat'] = mysql_real_escape_string($_GET['subcat']);
$color= $_SESSION['subcat'];
}
else {
$color= "";
};
I can echo selected in first drop down list, based on session value and that works, but a second one drop down list is not generated when page refreshes and i don't know where should i echo 'selected = "selected"' or maybe everything can be done only with javascript? Please help.
The code:
<div class="filter">
<form method="get" name="doublecombo" action="" id="filterform" >
<select name="example" id="exampl" size="1" onChange="redirect(this.options.selectedIndex)">
<option>All kinds</option>
<option>Women</option>
<option>Men</option>
</select>
<select name="subcat" size="1" id="subcategory">
<option value="lists.php">All colors</option>
</select>
<input type="button" name="test" value="Filter" onClick="go()">
</p>
<script>
<!--
/*
Double Combo Script Credit
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free JavaScripts here!
*/
var groups=document.doublecombo.example.options.length
var group=new Array(groups)
for (i=0; i<groups; i++)
group[i]=new Array()
group[0][0]=new Option("All colors","list.php")
group[1][0]=new Option("Pink","list.php?subcat=1 ")
group[1][1]=new Option("White","list.php?subcat=2")
group[1][2]=new Option("Green","list.php?subcat=3")
group[2][0]=new Option("Black","list.php?subcat=12")
group[2][1]=new Option("Blue","list.php?subcat=13")
group[2][2]=new Option("Grey","list.php?subcat=14")
group[2][3]=new Option("Brown","list.php?subcat=15")
var temp=document.doublecombo.subcat
function redirect(x){
for (m=temp.options.length-1;m>0;m--)
temp.options[m]=null
for (i=0;i<group[x].length;i++){
temp.options[i]=new Option(group[x][i].text,group[x][i].value)
}
temp.options[0].selected=true
}
function go(){
location=temp.options[temp.selectedIndex].value
}
//-->
</script>
</form></div>
you could set a cookie to hold the selected value, so if the user selects there choice and refreshes, you would then check if the cookie exists and then populate the menus accordingly.
Update:
This will store the selected values and repopulate the select menus if the user refreshes the page.
First select added onkeup:
<select name="example" id="exampl" size="1" onchange="redirect(this.options.selectedIndex)" onkeyup="redirect(this.options.selectedIndex)">
for the second select and as follows to check for changes
<select name="subcat" size="1" id="subcategory" onchange="checks(this)" onkeyup="checks(this)">
Now find the Line temp.options[0].selected=true and add this directaly below
createCookie("selected_option_1", x, 0);
if(x==0){
eraseCookie("selected_option_2");
}
then add these two new function say at the bottom of your script block
// checks if the Second Select has changed
function checks(oWhich){
createCookie("selected_option_2", oWhich.selectedIndex, 0);
}
// repopulate the options base on selection thats saved in the cookies
onload = function(){
if(readCookie("selected_option_1") != null) {
redirect(document.doublecombo.example.options.selectedIndex = readCookie("selected_option_1"));
if(readCookie("selected_option_2") != null) {
document.doublecombo.subcat.options.selectedIndex = readCookie("selected_option_2");
}
}
}
Finaly for these functions/scrip to work you will need
// The cookie script im using for the functions is located below include this and you chould ok. http://www.quirksmode.org/js/cookies.html#script
Now once the form has been submitted you GET the selected values as usual, and the REPOPULATE the menu, once you done with the cookie you could remove them.
If it's jQuery you are using you can try a short PHP tag on the page like this:
jQuery('#MyDropDown').val('<?php echo $_SESSION['MyStoredValue']; ?>');
If you are not using jQuery but straight JavaScript this would have the same effect:
document.getElementById("MyDropDown").value = '<?php echo $_SESSION['MyStoredValue']; ?>'

PHP dropdown sticky

I have a database populated drop down list.
$options4="";
while ($row = mysql_fetch_array($result)) {
$id=$row["Client_Code"];
$thing=$row["Client_Full_Name"];
$options4.="<OPTION VALUE=\"$id, $thing\">".$thing;
}
?>
<FORM name="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<SELECT NAME="ClientNamefour" OnChange="this.form.submit()">
<OPTION VALUE=0>Client
<?php echo $options4?>
</SELECT>
</FORM>
Once this changes it pulls a client name from a database and brings up some information there is a form that can be filled out to insert more information into a database. Once that form is filled out this page sends the information to another page with the code to insert the data into the database. Then I am using a header at the end of that code to send it back to this page. But when it comes back to this page I want it to comeback to the client they selected before and not a blank screen. So how do I make a DB populated list automatically comeback to the previous selection using php?
All you need to do is modify the way you construct the options to spot when you are creating the selected one, then add a SELECTED attribute to it...
//obtain current value from GET, POST or COOKIE value...
$current=isset($_REQUEST['ClientNamefour'])?$_REQUEST['ClientNamefour']:'';
while ($row = mysql_fetch_array($result)) {
$id=$row["Client_Code"];
$thing=$row["Client_Full_Name"];
$value="$id, $thing";
//figure out if we should select this option...
$sel=($value==$current)?'SELECTED':'';
$options4.="<OPTION $sel VALUE=\"$value\">".$thing;
}
One way to keep the value persistent would be to store it in the session, e.g. when you process the form
//assuming session_start() has been called...
if (isset($_POST['ClientNamefour']))
$_SESSION['ClientNamefour']=$_POST['ClientNamefour'];

Categories