Changing the content of a dropdown menu from a dropdown menu select - php

I have some dropdown menus. If I select one of them I want to change the other's content with something that is reliable with what i selected. How can I do that ? With html and php.
For example I have one table
Year with id_year and year
Stuff with id_stuf and stuff
If I select an year in the first dropdown menu , in the other drodown menu will show only the stuff from that year .
This is my content with the dropdown menus
<div class="view">
<form name="tabel" method="post" action="insertexamen.php">
<table>
<tr>
<td>Data</td>
<td><input type="date" name="data" value="data" required="required"/><br></td>
</tr>
<tr>
<td>An</td>
<td>
<?php
$sql_year="SELECT * FROM an";
$rez_year = mysqli_query($link,$sql_year);
echo "<select name=\"year\" >";
while($year=mysqli_fetch_array($rez_year))
{
echo "<option value=\"".$year['id_an']."\">".$year['grupa']."</option>";
}
echo "</select>";
?><br>
</td>
</tr>
<tr>
<td>Materie</td>
<td>
<?php
$sql_mat="SELECT * FROM materii";
$rez_mat = mysqli_query($link,$sql_mat);
echo "<select name=\"mat\" >";
while($mat=mysqli_fetch_array($rez_mat))
{
echo "<option value=\"".$mat['id_mat']."\">".$mat['numemat']."</option>";
}
echo "</select>";
?><br>
</td>
</tr>
<tr>
<td>Profesor</td>
<td>
<?php
$sql_proff="SELECT * FROM profesor";
$rez_proff = mysqli_query($link,$sql_proff);
echo "<select name=\"proff\" >";
while($proff=mysqli_fetch_array($rez_proff))
{
echo "<option value=\"".$proff['id_prof']."\">".$proff['numep']." ".$proff['prenumep']."</option>";
}
echo "</select>";
?><br>
</td>
</tr>
<tr>
<td>Asistent</td>
<td>
<?php
$sql_profff="SELECT * FROM profesor";
$rez_profff = mysqli_query($link,$sql_profff);
echo "<select name=\"profff\" >";
while($profff=mysqli_fetch_array($rez_profff))
{
echo "<option value=\"".$profff['id_prof']."\">".$profff['numep']." ".$profff['prenumep']."</option>";
}
echo "</select>";
?><br>
</td>
</tr>
<tr>
<td>Sala</td>
<td>
<?php
$sql_room="SELECT * FROM sala";
$rez_room= mysqli_query($link,$sql_room);
echo "<select name=\"room\" >";
while($room=mysqli_fetch_array($rez_room))
{
echo "<option value=\"".$room['id_s']."\">".$room['salaa']."</option>";
}
echo "</select>";
?><br>
</td>
</tr>
<tr>
<td>Tip</td>
<td>
<?php
$sql_type="SELECT * FROM examen";
$rez_type= mysqli_query($link,$sql_type);
echo "<select name=\"type\" >";
while($type=mysqli_fetch_array($rez_type))
{
echo "<option value=\"".$type['id_tip']."\">".$type['tip']."</option>";
}
echo "</select>";
?><br>
</td>
</tr>
<tr>
<td><input name="submit" type="submit" value="Trimite"/></td>
<td><input name="reset" type="reset" value="Reset"/></td>
</tr>
</table>

Are you looking for something like that:
<html>
<title>dropdownlist</title>
<head>
<script language="Javascript" type="text/javascript" >
function choix(formulaire)
{
var j;
var i = form1.boite1.selectedIndex;
if (i == 0)
for(j = 1; j <3; j++)
form1.boite2.options[j].text="";
else{
switch (i){
case 1 : var text = new Array( "London","Manchester","Birmingham");
break;
case 2 : var text = new Array("Paris","Marseille","Lyon");
break;
case 3 : var text = new Array("Berlin","Munich","Francfort");
break;
}
for(j = 0; j<3; j++)
form1.boite2.options[j+1].text=text[j];
}
form1.boite2.selectedIndex=0;
}
</script>
</head>
<body>
<form name="form1">
<select name="boite1" onChange="choix(this.form)">
<option selected>country</option>
<option>England</option>
<option>France</option>
<option>Germany</option>
</select>
<select name="boite2">
<option selected>cities</option>
<option></option>
<option></option>
<option></option>
</form>
</select>
</body>
</html>
if you want absolutely to do it using only html and php you will need to use some ajax because php is serverside and html is slient side. so for what you asy I would recommend the code above

Related

some combobox reset each other after selected

I have some combobox with onchange event, and they're reset each other when selected the orther one of them, does any suggest how to retain the value on the page? this my script :
<form method="POST" name="form1" action="<?php $_SERVER['PHP_SELF'];?>">
<table border="0">
<tr>
<td colspan="6"></td>
</tr>
<tr>
<td>
<select name="select_petugas1" style="width:18px;" onchange="this.form.submit('select_petugas1');"> //first combobox
<option></option>
<?php include 'dbconn.php';
$sql_peg1="SELECT * FROM users"; $result_peg1=$conn->query($sql_peg1);
while( $row_peg1=$result_peg1->fetch_assoc() ){
echo "<option>".$row_peg1['nama']."</option>";
}
?>
</select>
</td>
<td>
<?php
if(isset($_POST['select_petugas1'])){
$select_petugas1=$_POST['select_petugas1'];
echo "<input type='text' name='select_petugas1' value='".$select_petugas1."'>"; // Throw 1st result into the text box
$sql_NIP1="SELECT NIP FROM users WHERE nama='$select_petugas1'";
$result_NIP1=$conn->query($sql_NIP1);
$row_NIP1=$result_NIP1->fetch_assoc();
$NIP1=$row_NIP1['NIP'];
?>
</td>
<td> NIP</td>
<td>:</td>
<td><input type="text" name='NIP1' value="<?php echo $NIP1; ?>"></td>
</tr> <!-- child of first result -->
<tr>
<td colspan="5" bgcolor="blue"></td>
</tr>
<tr>
<td>
<select name="peg_2" style="width:18px;" onchange="submit(this)"><!--2nd combobox-->
<option></option>
<?php
$sql_peg2="SELECT nama FROM users";
$result_peg2=$conn->query( $sql_peg2 );
while ($row_peg2=$result_peg2->fetch_assoc()){
echo "<option value='".$row_peg2['nama']."'>".$row_peg2['nama']."</option>";
}
?>
</select>
</td>
<td>
<?php
if( isset($_POST['peg_2']) ){
$peg_2=$_POST['peg_2'];
echo "<input type='text' name='peg2' value='".$peg_2."'>"; // 2nd result throw into 2nd texbox
$sql_NIP2="SELECT NIP FROM users WHERE nama='$peg_2'";
$result_NIP2=$conn->query($sql_NIP2);
$row_NIP2=$result_NIP2->fetch_assoc();
?>
</td>
<td> NIP</td>
<td>:</td>
<td><input type='text' name='NIP2' value="<?php echo $row_NIP2['NIP'];?>"> <!--2nd child of result-->
<?php
}
}
if(isset($_POST['NIP2'])){
$NIP2=$_POST['NIP2'];
echo "<br /> NIP2 :".$NIP2."<br />";
}
mysqli_close($conn);
?>
</td>
</tr>
</table>
</form>
<form method="POST" name="wilayah" id="wilayah" action="<?php $_SERVER['PHP_SELF'];?>">
<table border="1">
<tr>
<td>
<select name="select_provinsi" onchange="submit(this)" style="width:18;">
<option selected>PROVINSI</option>
<?php
include 'dbconn.php';
$sql_prov="SELECT * FROM wilayah GROUP BY provinsi";
$result_prov=$conn->query($sql_prov);
echo "";
while($row_prov=$result_prov->fetch_assoc()){
$provinsi=$row_prov['provinsi'];
echo "<option value='".$provinsi."'>".$provinsi."</option>";
}
?>
</select>
<?php
if(isset($_POST['select_provinsi'])){
$select_provinsi=$_POST['select_provinsi'];
echo "
<input type='text' name='select_provinsi' value='".$select_provinsi."' placeholder='PROVINSI'>
</td>
</tr>";
$sql_kabkota="SELECT * FROM wilayah WHERE provinsi='$select_provinsi' GROUP BY kab_kota";
$result_kabkota=$conn->query($sql_kabkota);
?>
<tr>
<td>
<select name="select_kabkota" style="width:18px;" onchange="submit(this)"><option>KAB/KOTA</option>
<?php
while($row_kabkota=$result_kabkota->fetch_assoc()){
echo "<option>".$row_kabkota['kab_kota']."</option>";
}
?>
</select>
<?php
}
if(isset($_POST['select_kabkota'])){
$select_kabkota=$_POST['select_kabkota'];
?>
<input type="text" name="kab_kota" value="<?php echo $select_kabkota;?>">
<?php
}
mysqli_close($conn);
?>
</td>
</tr>
</table>
</form>
hope any suggestion for resolved of my problem with them,,
onchange="submit(this)" means that you want to submit the form when the value of the combobox changes. So, when the form is sent, the page reloads and you get the default value of your form.
To restore the chosen value, I would do something like :
<select name="select_kabkota" style="width:18px;" onchange="submit(this)">
<option>KAB/KOTA</option>
<?php
if(isset($_POST['select_kabkota']))
$select_kabkota=$_POST['select_kabkota'];
while($row_kabkota=$result_kabkota->fetch_assoc())
{
$selected = $select_kabkota == $row_kabkota['kab_kota'] ? 'selected="selected"' : '';
echo "<option ".$selected." >".$row_kabkota['kab_kota']."</option>";
}
?>
</select>

How do I make my drop down select menu persistently show the same data after a query is done using the menu?

So I am having an issue with a drop down selection box. What I am doing is having someone log into a database, and then the database shows all the tables available in the selection box. The user can then select the table they wish to see, hit select and bam! There's the table information.
I am, however having an issue getting the data in the selection box to persist after they hit select. For some reason, it just makes it empty. I'm using session variables, and maybe that effects it? I'm just now beginning to learn how that works too. Take a look at let me know what you think:
<?php
session_start();
if(!isset($_SESSION['session_level'])):
$_SESSION['session_level'] = 0; ?>
<? endif ?>
<?php
if(isset($_POST['host'])):
$_SESSION['host'] = $_POST['host'];
$_SESSION['dbname'] = $_POST['dbname'];
$_SESSION['username'] = $_POST['username'];
$_SESSION['pw'] = $_POST['pw'];
?>
<?php endif ?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Login Test</title>
</head>
<body>
<?
if (isset($_POST['return']))
{
$_SESSION['session_level'] = 0;
}
else if (isset($_POST['submit']))
{
try
{
$db = new PDO("mysql:host=".$_POST['host'].";dbname=".$_POST['dbname'], $_POST['username'], $_POST['pw']);
}
catch(Exception $error)
{
$_SESSION['session_level'] = 0;?>
<a href='<?= $_SERVER['PHP_SELF'] ?>'>Click here to return.</a>
<? echo "\n"; ?>
<?die("Connection to user database failed: " . $error->getMessage());
}
try
{
$db->setAttribute(PDO::ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
$query = "SHOW TABLES";
$results = $db->query($query)->fetchAll();
$_SESSION['session_level'] = 1;
}
catch(Exception $error)
{
echo "Problem with query!";
$_SESSION['session_level'] = 0;?>
<a href='<?= $_SERVER['PHP_SELF'] ?>'>Click here to return.</a>
<? }
}
?>
<?php if($_SESSION['session_level'] == 0){?>
<h1>Database Practice</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name='initialentry'>
<table border='0' style='text-align: center'>
<tr>
<td style='text-align: right;'>Enter host name:</td>
<td style='text-align: left;'>
<input type='text' name='host' value='localhost'>
</td>
</tr>
<tr>
<td style='text-align: right;'>Enter database name:</td>
<td style='text-align: left;'>
<input type='text' name='dbname' value='zxyx999'>
</td>
</tr>
<tr>
<td style='text-align: right;'>Enter user name:</td>
<td style='text-align: left;'>
<input type='text' name='username' value='zxyx999'>
</td>
</tr>
<tr>
<td style='text-align: right;'>Enter password:</td>
<td style='text-align: left;'>
<input type='password' name='pw' width='15' value='12345'>
</td>
</tr>
<tr>
<td style='text-align: right;'><input type="reset" name="reset" value="Reset"></td>
<td style='text-align: left;'><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form>
<?php }
else if ($_SESSION['session_level'] == 1)
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name='getForm'>
<select name='select'>
<? foreach($results as $row)
echo "<option value=" . $row[0] .">" .$row[0]. "</option>"; ?>
</select>
<input type="submit" name="selected" value="Select">
<input type="submit" name="return" value="Return to Main Screen">
</form>
<?php
if(isset($_POST['selected']))
{
try
{
$db = new PDO("mysql:host=".$_SESSION['host'].";dbname=".$_SESSION['dbname'], $_SESSION['username'], $_SESSION['pw']);
}
catch(Exception $error)
{
die("Connection to user database failed: " . $error->getMessage());
}
try
{
$query = $db->prepare("SELECT * FROM " . $_POST['select']);
$query->execute();
$header = true;
}
catch(Exception $error)
{
echo "Query failed.";
}
echo "</br>";
?>
<?php
echo "<table border='1'>";
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
if($header == 'true')
{
foreach($row as $index => $fieldValue)
{
echo "<td>";
echo $index;
echo"</td>";
}
echo "</tr>";
$header = 'false';
}
echo "<tr>";
foreach($row as $index => $fieldValue)
{
echo "<td>";
echo $fieldValue;
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
}
}
?>
</body>
</html>
If I well understand your problem then my advice 'll be to change your form and do it this way :
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name='getForm'>
<input type="hidden" name="selected" value="true">
<select name='select'>
<? foreach($results as $row)
echo "<option value=" . $row[0] .">" .$row[0]. "</option>"; ?>
</select>
<input type="submit" value="Select">
</form>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name='getForm'>
<input type="hidden" name="return" value="true">
<input type="submit" value="Return to Main Screen">
</form>
It means you must create 2 forms instead of 1 with because the name value on a submit button is not intrepreted the same way on all browser. So by removing and replacing it by an input type hidden it 'll assure the field 'll exist after submitting forms.
When you repopulate the select list, if the option selected matches the option being populated, then you can make that bit of code <option selected value=" and that option will now be the default selected item at the moment.
I realize the below code isn't PHP, my point is that it should be a simple If statement, to include the selected tag into the option.
/*
Adding the "selected" tag to an option, makes it the default.
*/
<select>
<option value="" style="display:none;">Select a Value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br /><br />
<select>
<option value="" style="display:none;">Select a Value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected>3</option>
<option value="4">4</option>
</select>

Auto updation of product price when its corresponding quantiy changes using jquery in a shopping cart

I am trying to develop just like a following siteenter link description here
Here when the user tries to purchase many items, his cart is displayed.And he can try to change the quantity of any item.When he changes the quantity of an item,the corresponding price of that item has to change automatically.It is done using jquery. I will provide my code here.
foreach( $_SESSION['r'] as $key=>$ar):
$cnt++;
?> <tr>
<td align="center"><?php echo $ar['Name']?></td>
<td align="center"><?php echo $ar['Price']?></td>
<td align="center"> // Quantity is given as dropdownlist.Each list has seperate select id that is generated dynamivally.such as qty1,qty2,etc.
<select class="myclass" name="qty" id='qty<?php echo $cnt;?>' onChange="get_price(this.value,<?php echo $ar['Price']?>,<?php echo $cnt;?>)">
<?php for ($i=1; $i<=100; $i++) {
$y="";
if( $i==$_SESSION['r'][$key]['Quantity']){
$y="selected";
}
echo "<option ";
echo "value=\"$i\" ".$y.">", $i, "</option>\n";
} ?>
</select>
</td>
<?php $x=$x+$ar['Quantity']; ?>
<td name="price"><span id="priceDisplay<?php echo $cnt;?>"><?php echo $ar['Total']; ?></span></td>
<input type='hidden' name='id' id="pid" value='<?php echo $ar['Id']; ?>'>
<input type='hidden' name='price' id="pprice" value='<?php echo $ar['Price'] ?>' class="input">
The next code is my jquery code
function get_price(val,price,cnt){
var price1 = val * price;
document.write(('<span id="priceDisplay"+cnt></span>\n'));
Here I am calculating the price when the quantity changes.But my problem is that I don't know how to display the calculated price in the appropriate column. variable cnt is the row id passed from php. Please help me.
<?php
session_start();
include('head.php');
?>
<!DOCTYPE HTML>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function get_price(val,price,cnt)
{
var price1 = val * price;
$("#priceDisplay"+cnt).html(price1);
</script>
<?php
if(empty($_SESSION['items'])){ ?>
<center><b><font color="red">There are no products in your cart!!</font> </b></center>
<?php
}
else
{
?>
<b><center><font color="green"> Your Shopping Cart!!</font></center> </b><br><br>
<form name="formview" action="ajaxview.php" method="post">
<?php $count=0; ?>
<table align="center" width="50%" cellpadding="1px" cellspacing="3px" border="1" bgcolor="lightblue">
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th>Remove</th>
</tr>
<?php
foreach( $_SESSION['r'] as $key=>$ar):
$cnt++;
?> <tr>
<td align="center"><?php echo $ar['Name']?></td>
<td align="center"><?php echo $ar['Price']?></td>
<td align="center">
<select class="myclass" name="qty" id='qty<?php echo $cnt;?>' onChange=get_price(this.value,<?php echo $ar['Price']?>,<?php echo $cnt;?>,) >
<?php for ($i=1; $i<=100; $i++) {
$y="";
if( $i==$_SESSION['r'][$key]['Quantity']){
$y="selected";
}
echo "<option ";
echo "value=\"$i\" ".$y.">", $i, "</option>\n";
} ?>
</select>
</td>
<?php $x=$x+$ar['Quantity']; ?>
<td name="price"><span id="priceDisplay<?php echo $cnt;?>"><?php echo $ar['Total']; ?></span></td>
<input type='hidden' name='id' id="pid" value='<?php echo $ar['Id']; ?>'>
<input type='hidden' name='price' id="pprice" value='<?php echo $ar['Price'] ?>' class="input">
<td><input type='checkbox' name='remove' value='Remove' onCheck="$(this).closest('tr').remove();">
<?php $tt[]=$ar['Total'];?>
</tr>
<?php
endforeach;
?>
</table>
</form>
<!--<table align="right">-->
<?php foreach($tt as $t)
{
$count=$count+$t;
}
?>
<br>
<br>
<b><center><div class="total"> Total:<span id="tot"><?php echo $count; ?></span></div></center></b>
<b><div class="cart">Your Cart:<span class="ycart"><?php echo $x; ?></span> </div></b>
Hope it helps,
function get_price(val,price,cnt){
var price1 = val * price;
document.getElementById('priceDisplay'+cnt).innerHTML =price1;
//$('#priceDisplay'+cnt).html(price1); //jquery
}
Using Jquery to acheive this,
$(document).ready(function() {
$(".myclass").change(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
$("#priceDisplay_"+identifier).html(Total);
GrandTotal();
});
GrandTotal();
});
function GrandTotal(){
var GrandTotal=0;
$(".myclass").each(function(){
var identifier = $(this).attr('id');
var Qty = $(this).val();
var Price = $("#price_"+identifier).val();//price value
var Total = Qty * Price;
GrandTotal += Total;
$("#priceDisplay_"+identifier).html(Total);
});
$("#GrandTotal").html(GrandTotal);
}
function RemoveCart(ob){
var IdForRemove =ob.value;
$.ajax({
type: "POST",
url: "RemoveCart.php",
dataType:'json',
data: { id: IdForRemove}
})
.done(function( data ) {
$("#GrandTotal").html(data.Grandtotal);
$("#"+IdForRemove).remove();
});
return false;
}
<table>
<?php
$cnt =0;
// session_start();
// $_SESSION['r'] = array('0'=>array('Name'=>'test 1','Price'=>'50.5','Id'=>'1', 'Quantity'=>'3'), '1'=>array('Name'=>'test 2','Price'=>'100','Id'=>'2', 'Quantity'=>'4'), '2'=>array('Name'=>'test 3','Price'=>'150','Id'=>'3', 'Quantity'=>'5'));
$CartR = $_SESSION['r'];
foreach($CartR as $key=>$ar):
$Identifier = 'qty_'.$cnt;
?>
<tr id="<?php echo $ar['Id']; ?>">
<td align="center"><?php echo $ar['Name']?></td>
<td align="center"><?php echo $ar['Price']?></td>
<td align="center"> // Quantity is given as dropdownlist.Each list has seperate select id that is generated dynamivally.such as qty1,qty2,etc.
<select class="myclass" name="qty" id='<?php echo $Identifier;?>' >
<?php for ($i=1; $i<=100; $i++) {
$y="";
if( $i==$ar['Quantity']){
$y='selected="selected"';
}
echo "<option value='".$i."' $y> $i</option>\n";
} ?>
</select>
</td>
<?php $x=$x+$ar['Quantity']; ?>
<td name="price"><span id="priceDisplay_<?php echo $Identifier;?>"><?php echo $ar['Total']; ?></span></td>
<input type='hidden' name='id' id="pid_<?php echo $Identifier;?>" value='<?php echo $ar['Id']; ?>'>
<input type='hidden' name='price' id="price_<?php echo $Identifier;?>" value='<?php echo $ar['Price'] ?>' class="input">
<td><input type="checkbox" onclick="RemoveCart(this)" value="<?php echo $ar['Id']; ?>"> Remove
</tr>
<?php $cnt++; endforeach; ?>
</table>
Grand Total: <div id="GrandTotal"></div>
Create new file "RemoveCart.php" and below lines into that page,
<?php session_start();
if(isset($_POST['id'])){
$toBeRemove =$_POST['id'];
$CartR =$_SESSION['r'];
foreach($CartR as $key=>$Cart){
if($Cart['Id']==$toBeRemove){
unset($_SESSION['r'][$key]);
}
}
$CartR = $_SESSION['r'];
$Grandtotal =0;
foreach($CartR as $key=>$Cart){
$Grandtotal += $Cart['Quantity'] * $Cart['Price'];
}
echo json_encode(array('Grandtotal'=> "$Grandtotal"));
}
?>
Replace this:
document.write(('<span id="priceDisplay"+cnt></span>\n'));
With this:
document.getElementById("priceDisplay"+cnt).innerHTML=price1;
Using Jquery:
$("#priceDisplay"+cnt).html(price1);
You want it in jquery. Use
$("#id").html("hello World");
Change the id to the id you want to use. And the text as well

Update value in the database when done editing using PHP/jQuery/Ajax

I have a table something like this:
Product SellingPrice Cost Profit
Product 1 49 45 4
Product 2 54 50 4
When i put value in the profit column the sellingprice will calculate. I fetched the cost value from the database. I'm done working with the calculation using jQuery but I'm stuck on how to update it in the database. Could someone guide me about the server side implementation?
Here is my code:
<html>
<head>
<title>Content Management System</title>
<script>
//calculate the selling price
$(document).ready(function(){
$('tr').each(function(){
var result = 0;
$(this).find("input[name=cost],input[name=profit]").each(function(){
result += (+$(this).val());
});
$(this).find("input[name=sellingprice]").val(result).css("background-color", "green");
});
});
</script>
</head>
<body>
<table>
<tr>
<td><center>ID</center></td>
<td><center>Product</center></td>
<td><center>Selling Price</center></td>
<td><center>Current Cost</center></td>
<td><center>Profit</center></td>
</tr>
<?php
$result = mysql_query("SELECT id, product, cost FROM inventory");
while ($myrow = mysql_fetch_row($result))
{
?>
<tr>
<td>
<?php echo $myrow[0]; ?>
</td>
<td>
<?php echo $myrow[1]; ?>
</td>
<td>
<?php echo "<input type='text' name='sellingprice' size='10' readonly='true'/>"; ?>
</td>
<td>
<?php echo "<input type='text' name='cost' size='10' value='$myrow[2]' readonly='true'/>"; ?>
</td>
<td>
<?php echo "<input type='text' name='profit' size='10' />"; ?>
</td>
</tr>
<?php
}
?>
</table>
</center>
</body>
</html>
change your html and create a new php file to handle your form submission.
in php get the values through $_GET[""] and insert them into table.
<body>
<form name="some_name" id="form1" action="somephpfilename.php">
<table>
<tr>
<td><center>ID</center></td>
<td><center>Product</center></td>
<td><center>Selling Price</center></td>
<td><center>Current Cost</center></td>
<td><center>Profit</center></td>
</tr>
<?php
$result = mysql_query("SELECT id, product, cost FROM inventory");
while ($myrow = mysql_fetch_row($result))
{
?>
<tr>
<td>
<?php echo $myrow[0]; ?>
</td>
<td>
<?php echo $myrow[1]; ?>
</td>
<td>
<?php echo "<input type='text' name='sellingprice' size='10' readonly='true'/>"; ?>
</td>
<td>
<?php echo "<input type='text' name='cost' size='10' value='$myrow[2]' readonly='true'/>"; ?>
</td>
<td>
<?php echo "<input type='text' name='profit' size='10' />"; ?>
</td>
</tr>
<?php
}
?>
</table>
</center>
<input type="submit" name="update" value="update to db">
<form>
</body>
You add form tag to your table rows and when form is submitted, you grab / validate incoming data and run UPDATE query on your table by ids. Also, you need to change your input elements to use Arrays:
echo "<input type='text' name='sellingprice[".$myrow[0]."]' size='10' readonly='true'/>";
Something like that...

Populating dropdown - PHP Ajax MySQL

I have 2 dropdowns on my HTML page : The first drop down contains the database column names based on which the the second dropdown would be populated i.e.
I have a single table with fields: <Student Name, Degree, City> and following would be the entries;
1. "A", "BS", "New York"
2. "B", "BS", "Chicago"
3. "C", "MS", "Boston"
4. "D", "MS", "New York"
So my first dropdown would contain the column names i.e. "Degree" and "City".
If I select "Degree", the 2nd dropdown should populate "BS" and "MS" and if I select "City", the 2nd dropdown should select "New York", "Boston" and "Chicago".
How can I go about with the implementation?
[Adding my code]:
the changeSecond(first) method remains exactly the same as you suggested
<body>
<form method="POST" action="" name="mainForm">
<table>
<tr>
<td> Filter by: </td>
<td>
<div id="first">
<select onChange="changeSecond(this.value)">
<option value="1">All</option>
<option value="2">Degree</option>
<option value="3">City</option>
</select>
</td>
</tr>
<tr>
<td>&nbsp</td>
<td>
<div id="second">
<select name="val">
<option value=""></option>
</select>
</div>
</td>
</tr>
</table>
</form>
</body>
And this is the second_script.php as you suggested:
<?
$link = mysql_connect("localhost", "root", "");
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
if (mysql_select_db("myDatabase", $link))
{
$first=mysql_real_escape_string($_REQUEST["first"]);
$query="SELECT ".$first." FROM myTable GROUP BY ".$first;
$data=mysql_query($query);
echo "<select id=\"second\">";
while($row=mysql_fetch_row($data))
{
echo "<option value=\"".$row[0]."\">".$row[0]."</option>";
}
echo "</select>";
}
echo mysql_error();
?>
code for the main file in which you want to populate drop down based on other
in below example i show localities in child dropdown for that city that is selected in parent drop down
<script type="text/javascript">
function city_locality(val)
{
// alert (val);
url="<?php echo $this->baseurl ?>/components/com_ezportal/includes/query.php";
data="stid="+val;
$.post(url,data,function(data){
$("#locid").html(data);
});
}
</script>
<select name="filter_1state" id="filter_1state" onChange="city_locality(this.value)">
<option value="0">-- Select City --</option>
<option value="1">Lahore</option>
<option value="2">Karachi</option>
<option value="3">Islamabad</option>
<option value="4">Quetta</option>
<option value="5">Multan</option>
</select>
code for the file query.php
<?php
$link = mysql_connect('localhost', 'root', '');
mysql_select_db('mydatabase');
if (isset($_POST['stid']))
{
$stid = $_POST['stid'];
$query= mysql_query("SELECT id,ezcity FROM tbl_locality WHERE stateid = '".$stid."' GROUP BY ezcity");
?>
<option value="0">-- Select Locality --</option>
<?php
while($row = mysql_fetch_array($query))
{
?>
<option value="<?php echo $row['id']?>"><?php echo $row['ezcity']?> </option>
<?php
}
}
?>
If you want a more dynamic solution (that will accommodate changes to the background DB) you can do something like this on your page:
<script>
function changeSecond(first){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var res=xmlhttp.responseText;
document.getElementById("second").innerHTML=res;
}
}
xmlhttp.open("GET","second_script.php?first="+first,true);
xmlhttp.send();
}
</script>
...
<select onChange="changeSecond(this.value)">
<option value="Degree">Degree</option>
<option value="City">City</option>
</select>
<div id="second"><select><option value=""></option></select></div>
and then a script similar to:
<?php
//database connection
$first=mysql_real_escape_string($_REQUEST["first"]);
$query="SELECT ".$first." FROM tablename GROUP BY ".$first;
$data=mysql_query($query);
echo "<select>";
while($row=mysql_fetch_row($data)){
echo "<option value=\"".$row[0]."\">".$row[0]."</option>";
}
echo "</select>";
?>
I guess for real flexibility you'd also want to dynamically populate that first one using mysql_field_name in another script similar to above
You could either have all the dropdown needed preloaded and hidden, and show them when the 'change' event is triggered in the first dropdown, or have two dropdowns and empty it on that same 'change' event.
If you choose the second approach you should buffer the data to insert in the dropdown list, partially or totally
You can use ajax for this purpose
eg1.html
<html>
<head><title></title>
</head>
<body>
<form method="POST" action="" name="mainForm">
<table>
<tr>
<td> Filter by: </td>
<td>
<div id="first">
<select id="first_dropdown">
<option value="All">All</option>
<option value="Degree">Degree</option>
<option value="City">City</option>
</select>
</td>
</tr>
<tr>
<td>&nbsp</td>
<td>
<div id="second">
<select id="second_dropdown">
</select>
</div>
</td>
</tr>
</table>
</form>
</body>
</html>
<script src = "https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#first_dropdown').change(function(){
$.ajax({
'type' : 'post',
'url' : 'getDropdownOptions.php',
'data': 'first=' + $(this).val(),
'success' : function(data) {
$('#second_dropdown').html(data);
}
});
});
});
</script>
getDropdownOptions.php
<?php
$link = mysql_connect("localhost", "root", "");
if (!$link) {
die('Could not connect: ' . mysql_error());
}
if (mysql_select_db("myDatabase", $link)) {
$first = mysql_real_escape_string($_REQUEST["first"]);
$query = "SELECT " . $first . " FROM myTable GROUP BY " . $first;
$data = mysql_query($query);
$rtn_data = '';
while ($row = mysql_fetch_row($data)) {
$rtn_data .= "<option value=\"" . $row[0] . "\">" . $row[0] . " </option>";
}
echo $rtn_data;
exit;
}
echo mysql_error();
?>
Divyesh here, your answer is
==============================
edit.php
==============================
<!-- edit.php -->
<?php
include("config.php");
$id=$_REQUEST['id'];
echo $id;
$query=mysqli_query($con,"SELECT * FROM register r
INNER JOIN country c ON r.cuid = c.cuid
INNER JOIN state s ON r.sid = s.sid
INNER JOIN city ct ON r.cid = ct.cid where id='$id'");
while($r=mysqli_fetch_array($query))
{
$fn=$r['firstname'];
$add=$r['address'];
$gn=$r['gender'];
$hobby=$r['hobby'];
$h=explode(',',$hobby);
$q=array('reading','traveling','cricket','drawing');
$country=$r['cuid'];
$state=$r['sid'];
$city=$r['cid'];
echo $gn;
$edu= $r['education'];
$email=$r['email'];
$pass=$r['password'];
$conpass=$r['conpassword'];
$phno=$r['phoneno'];
}
?>
<html>
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'cuid='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html(html);
}
});
}else{
$('#state').html(html);
$('#city').html(html);
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'sid='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html(html);
}
});
});
</script>
</head>
<body>
<form method="post" action="update.php">
<table border="1" align="center">
<caption>Edit user data</caption>
<tr>
<td>First name</td>
<td><input type="text" name="fn" value="<?php echo $fn;?>"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="add" value="<?php echo $add;?>"></td>
</tr>
<tr>
<td>Gender</td>
<td><input type="radio" name="gn" value="male" <?php echo ($gn=='male')?'checked':'' ; ?> size="17">Male
<input type="radio" name="gn" value="female" <?php echo ($gn=='female')?'checked':'' ; ?> size="17">Female
</td>
</tr>
<tr>
<td>Hobby</td>
<td><input type="checkbox" name="hobby[]" value="reading" <?php if(in_array('reading',$h)){echo ("checked:'checked'");}?> >reading
<input type="checkbox" name="hobby[]" value="traveling" <?php if(in_array('traveling',$h)){echo ("checked:'checked'");}?> >traveling
<input type="checkbox" name="hobby[]" value="cricket" <?php if(in_array('cricket',$h)){echo ("checked:'checked'");}?> >cricket
<input type="checkbox" name="hobby[]" value="drawing" <?php if(in_array('drawing',$h)){echo ("checked:'checked'");}?> >drawing</td>
</tr>
<?php
$query = mysqli_query($con,"SELECT * FROM country");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
?>
<td>Country</td>
<td><select name="country" id="country">
<option value="<?php echo $country;?>"><?php echo $country;?></option>
<?php
if($rowCount > 0)
{
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['cuid'].'">'.$row['country'].'</option>';
}
}
else
{
echo '<option value="">Country not available</option>';
}
?>
</select>
</td></tr>
<tr>
<td>State</td>
<td>
<select name="state" id="state">
<option value="<?php echo $state;?>"><?php echo $state;?></option>
</select>
</td></tr>
<tr>
<td>City</td>
<td>
<select name="city" id="city">
<option value="<?php echo $city;?>"><?php echo $city;?></option>
</select>
</td>
</tr>
<tr>
<td>Education</td>
<td><input type="text" name="edu" value="<?php echo $edu;?>"></td>
</tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email;?>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="pass" value="<?php echo $pass;?>"></td>
</tr>
<tr>
<td>Confirm password</td>
<td><input type="text" name="conpass" value="<?php echo $conpass;?>"></td>
</tr>
<tr>
<td>Phone no</td>
<td><input type="text" name="phno" value="<?php echo $phno;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value="<?php echo $id;?>">
<input type="submit" name="update" value="update"></td>
</tr>
</table>
</form>
</body>
</html>
================
<h3>ajaxData.php</h3>
================
<!--ajaxData.php-->
<?php
//Include database configuration file
include("config.php");
if(isset($_POST["cuid"]) && !empty($_POST["cuid"]))
{
//Get all state data
$query = mysqli_query($con,"SELECT * FROM state WHERE cuid = ".$_POST['cuid']."");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
//Display states list
if($rowCount > 0)
{
echo '<option value="">Select state</option>';
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['sid'].'">'.$row['state'].'</option>';
}
}
else
{
echo '<option value="">State not available</option>';
}
}
if(isset($_POST["sid"]) && !empty($_POST["sid"]))
{
//Get all city data
$query = mysqli_query($con,"SELECT * FROM city WHERE sid =".$_POST['sid']."");
//Count total number of rows
$rowCount = mysqli_num_rows($query);
//Display cities list
if($rowCount > 0)
{
echo '<option value="">Select city</option>';
while($row = mysqli_fetch_array($query))
{
echo '<option value="'.$row['cid'].'">'.$row['city'].'</option>';
}
}
else
{
echo '<option value="">City not available</option>';
}
}
?>

Categories