Sanitize HTML in SQL query with PHP function - php

So I have a PHP page with a drop down form that when an option is selected, it uses an AJAX script to query a result from the same MySQL table. For the most part, it works like expected. However, some results (specifically, options that have " or ' in the name) are not being set properly to the variable for the AJAX/GET script. Here is my main PHP script:
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css" media="screen" />
<title>Add Inventory</title>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getsku.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
session_start();
require_once('includes/config.inc.php');
require_once('includes/functions.inc.php');
// Check login status -- if not logged in, redirect to login screen
if (check_login_status() == false) {
redirect('login.php');
}
$thisPage='add';
include('includes/navbar.inc.php');
?>
<h1>Add New Inventory Record</h1>
<form method="POST" action="submitadd.php" />
<table id="add">
<tr>
<td class="headings"><b>Species:</b></td>
<td><select name="species:" onchange="showUser(this.value)">
<option value="select">Choose a Species</option>
<?php
$prodquery="SELECT name FROM products ORDER BY name ASC";
$result=mysqli_query($con,$prodquery) or die(mysqli_error($con));
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
?>
</select>
</td>
</tr>
<div id='txtHint' />
<tr>
<td class="headings"><b>Fry Count:</b></td>
<td><input type="text" name="frycount" value="<?php echo $row['quantityfry']; ?>" size="35" maxlength="4" /></td>
</tr>
<tr>
<td class="headings"><b>Juvie Count:</b></td>
<td><input type="text" name="juviecount" value="<?php echo $row['quantityjuv']; ?>" size="35" maxlength="4" /></td>
</tr>
<tr>
<td class="headings"><b>Adult Count:</b></td>
<td><input type="text" name="adultcount" value="<?php echo $row['quantityadult']; ?>" size="35" maxlength="4" /></td>
</tr>
<tr>
<td class="headings"><b>Notes:</b></td>
<td><input type="text" name="notes" value="<?php echo $row['notes']; ?>" size="35" maxlength="255" /></td>
</tr>
<tr>
<td class="headings"><b>Location:</b></td>
<td><select name="location">
<?php
$options = set_and_enum_values($con, 'inventory', 'location');
foreach($options as $option):
?>
<option><?php echo $option ?></option>
<?php endforeach; ?>
</select></td>
</tr>
<tr>
<td class="headings"><b>Owner:</b></td>
<td><select name="owner">
<?php
$options = set_and_enum_values($con, 'inventory', 'owner');
foreach($options as $option):
?>
<option><?php echo $option ?></option>
<?php endforeach; ?>
</select></td>
</tr>
</table>
<br />
<input type="submit" name="submit" value="submit" class="button1" />
</form>
</body>
</html>
And here is getsku.php, which is called by the AJAX script:
<?php
$q = html_entity_decode($_GET['q']);
require_once('includes/config.inc.php');
$sql="SELECT sku FROM products WHERE name = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo "<td><input type='hidden' name='sku' value='" . $row['sku'] . "' readonly='readonly' size='35' /></td>";
}
mysqli_close($con);
?>
I've been doing some testing in Firebug and here is a specific example. The row of data is:
name = Lethrinops albus "Kande Island"
sku = HAP002
There is other data, but not of a concern for this. So when the dropdown selects Lethrinops albus "Kande Island", I want HAP002 set to a hidden field and passed to the submit button on this form. Using Firebug, I can see this under Params:
q Lethrinops albus "Kande Island"
Which is correct. Here is another row of data:
name = Cynotilapia afra "Lion's Cove"
sku = MBN002
But within Firebug, I see this under Params:
q Cynotilapia afra "Lion
Which is not correct. I'm assuming I need to sanitize the HTML result, and I found a function that may help:
function htmlsan($htmlsanitize){
return $htmlsanitize = htmlspecialchars($htmlsanitize, ENT_QUOTES, 'UTF-8');
}
But I'm not sure if this is what I need, and how to use it. Can anyone point me in the right direction please?

First of all, you should never construct an SQL query this way:
$q = html_entity_decode($_GET['q']);
$sql="SELECT sku FROM products WHERE name = '".$q."'";
It's not a good practice, and there are security issues like SQL Injection
To solve all your sanitations problems (and many others) I recommend you to use PHP Data Objects (PDO) to all your SQL connections.
Especially take a look at this answer How can I prevent SQL injection in PHP?
Use this function mysql-real-escape-string.php to sanitize you input data in MySQL query.
[EDITED]
Answer your question.
The problem is not in your SQL query. It is at <option value='problem is here!'>.
You should use htmlentities to correctly escape the single-quote when name = Cynotilapia afra "Lion's Cove".
echo "<option value='" . htmlentities($row['name']) . "'>" . $row['name'] . "</option>";
You may need to use html_entity_decode to decode (the reverse operation) in getsku.php.

Since you're passing data via GET you need to urlencode() the strings to pass them to the next page. Do not decode them in the next script. The superglobals are already decoded.
Once you're in the next script you should use your DB extension's escape functions to use the $_GET param in your SQL query.

Related

display the retrieved content after choose the option from drop down list in different places using ajax

I have a table which has a dynamic content.
the table contains a drop down list, where the user needs to choose an option then the displayed data will be returned using ajax.
currently it's work BUT the problem is that it's working only with the first row.
After l choose from the drop down list in the second row the result was displayed on
the first row :"/ !!
table code
<table class="bordered" >
<tr class="bordered">
<?php
$qry=mysql_query("SELECT *
FROM `order` ");
//Check whether the query was successful or not
$qry1="SELECT *
FROM `order` ";
$result=mysql_query($qry1);
if(mysql_num_rows($qry)>0){
?>
<th>delete</th><th>edit</th><th>staff info</th><th>staff</th><th>ex</th><th>phone</th><th>name</th><th>id</th><th>quantity</th><th>status</th><th>time</th><th>date</th><th>order number</th><th></th>
</tr>
<?php
while($info = mysql_fetch_array( $result ))
{
$idem = $info['emp_id'];
$q="select * from empoyee where emp_id= '".$idem."';";
$r=mysql_query($q);
?>
<tr>
<td>
<form method="POST" action="delete_asu.php">
<input type="image" src="delete1.png" width="25%" height="20%"/>
<input type="hidden" name="delete_id" value="<?php echo $info['order_num']; ?>" />
</form></td>
<td>
<?php $id=$info['order_num'];
echo '<form method="POST" action="update_asu_form.php?id='.$id.'">' ?>
<input type="image" src="settings-24-128.png" width="20%" height="15%"/>
</form></td>
<td id="txtHint"></td>
<td>
<select name="users" onchange="showUser(this.value)">
<option></option>
<?php
$sql=mysql_query("SELECT asu_name from asu_staff");
while($row = mysql_fetch_array($sql)){
echo "<option>" .$row["asu_name"]. "</option>";
}
?>
</select>
</td>
<?php
while($row = mysql_fetch_array( $r ))
{
?>
<td><?php echo $row['ex']; ?></td><td><?php echo $row['phone']; ?></td><td><?php echo $row['emp_name']; ?></td><td><?php echo $row['emp_id']; ?></td>
<?php
}
?>
<td><?php echo $info['quantity']; ?></td><td><?php echo $info['status']; ?></td>
<td><?php echo $info['time']; ?></td><td><?php echo $info['date']; ?></td>
<td><?php echo $info['order_num']; ?></td><td><input type="radio" name="choose" value="<?php echo $info['order_num']; ?>" /></td>
</tr>
<?php
}
}
else echo "<h1>no orders</h1>";
?>
</table>
The ajax code
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
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)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
The php code
$q=$_GET["q"];
$sql="SELECT * FROM asu_staff WHERE asu_name = '".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<table>";
echo "<tr> <td>" . $row['asu_id'] . " </td><td>staff id</td></tr>";
echo "<tr> <td>" . $row['phone'] . " </td><td>staff phone</td></tr>";
echo "</table>";
Yaaah It's work
the idea:
Alhamdullilallah it's working perfectly now :D
the problem was from the id of the where I retrieve the content
I make an incremental id and send it to the ajax , then it's work
The value that is given by the select is what is in the value="" attribute on each option. In your case you need to change the code displaying the options to:
<select name="users" onchange="showUser(this.value)">
<option value="" selected></option>
<?php
$sql=mysql_query("SELECT asu_name from asu_staff");
while($row = mysql_fetch_array($sql)){
echo "<option value=\"".$row["asu_name"]."\">" .$row["asu_name"]. "</option>";
}
?>
</select>
Try this.
p.s. you could select an id with the name in your query, then use the id in the value="" attribute. Your query in your php code could then use the id in stead of the name.

Firefox does not submit my form

I have a php application that fetches the requests from mysql database and displays them for further approval. The form is fetched from send_req.php and is displayed inside the div on showrequests.php. This is the code for send_req.php
<table style="border:0;border-color:transparent">
<tr style="background-color:lightblue">
<td>Product ID</td>
<td>Name</td>
<td>Quantity</td>
<td><input type="checkbox" name="selectAll" /></td>
<td>Authorized Quantity</td>
</tr>
<form method="post" action="send_req.php">
<?php
$reqNum = $_POST['rId'];
echo "<h3>Request # $reqNum</h3>";
$showReqs = mysql_query("Select * from request where request_number='".$reqNum."' and status=0");
while($resultA = mysql_fetch_array($showReqs))
{
$rBy = $resultA['requested_by'];
$rTime = $resultA['request_time'];
$rId = $resultA['id'];
$pId = $resultA['product_id'];
$getPrName = mysql_query("select name from products where id='$pId'");
$prN = mysql_fetch_array($getPrName);
$prName = $prN['name'];
$rQuantity = $resultA['requested_quantity'];
$status = $resultA['status'];
?>
<tr>
<input type="hidden" name="rId[]" value="<?php echo $rId; ?>"/>
<td style="background-color:orange"><input type="text" name="prId[]" value="<?php echo $pId; ?>" readonly="readonly" style="border:0px"/></td>
<td style="background-color:orange"><input type="text" name="prName[]" value="<?php echo $prName; ?>" readonly="readonly" style="border:0px"/></td>
<td style="background-color:orange"><input type="text" name="quantity[]" value="<?php echo $rQuantity; ?>" readonly="readonly" style="border:0px"/></td>
<td style="background-color:orange"></td>
<td><input type="text" name="pQuantity[]" /></td>
</tr>
<?php }
?>
<tr>
<td></td>
<td></td>
<td></td>
<input type="hidden" name="rNum" value="<?php echo $reqNum; ?>" />
<td></td>
<td><input type="submit" name="submitReq" value="Send" id="submit_req" style="backgroundColor:Transparent;border:0;color:blue;width:100;"/></td>
</tr>
</form>
</table>
<?php
echo "Requested By:$rBy at ".substr($rTime,11,18)." ".substr($rTime,0,10);
?>
This is the showrequests.php page
<html>
<head>
<script type="text/javascript">
function getRequest(ob)
{
var id = ob.id;
if(window.XMLHttpRequest)
{
ajaxOb = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
ajaxOb = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxOb.open("POST", "send_req.php");
ajaxOb.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxOb.send("rId=" + id);
ajaxOb.onreadystatechange = function()
{
if(ajaxOb.readyState == 4)
{
if(ajaxOb.status == 200)
{
document.getElementById("showTable").innerHTML = ajaxOb.responseText;
}
}
}
}
</script>
</head>
<body>
<?php
$mysql_con = mysql_connect("localhost","root","") or die("Could not connect ".mysql_error());
$mysql_db = mysql_select_db("cart",$mysql_con) or die("Unable to select db ".mysql_error());
echo "<h2 align='center'>Pending Requests</h2>";
$showReq = mysql_query("Select distinct(request_number) as rNums from request where status=0");
?>
<div style="float:left;margin-right:15px;">
<br/>
<?php
while($result = mysql_fetch_array($showReq))
{
$rNum = $result['rNums'];
?>
<input type="button" name="fetchReq" id="<?php echo $rNum; ?>" value="<?php echo "Request # $rNum"; ?>" style="margin-bottom:5px;backgroundColor:Transparent;border:0;color:blue;width:100;text-Decoration:underline" onclick="getRequest(this)"/>
<?php
echo "<br/>";
}
?>
</div>
<div id="showTable" style="float: left">
</div>
</body>
</html>
My problem now is that everything works fine in chrome and IE but the form is not submitted when i click the submit button in firefox. I am using firefox 20.0.1. Update: I have removed the html,head and body tags from send_req.php
still not working
form is not allowed inside table. Please see also
Form inside a table
Regards,
Michael
Reminder : the structure of an HTML document is :
<!-- No div before html tag -->
<!DOCTYPE html> <!-- Doctype for HTML5 ; use whatever doctype you need -->
<html>
<head>
</head>
<!-- No div before body tag -->
<body>
<!-- Divs only belongs here -->
</body>
</html>
<!-- No div after html tag -->
If you don't follow this basic structure, you're forcing the browser to interpret your invalid code (+ quirks mode when you don't provide a doctype).
Some browser guess well what you tried to do, others don't, as Firefox might.
Please use a HTML validator as W3's validator to check your syntax.

PHP page is storing form input variables after user submits

I wasn't sure what else to call the title...I have a PHP page that accesses a certain MySQL database, pulls the values from the table, and places them in an HTML form (POST method - PHP_SELF). The user can then view the values, alter them as they wish, and submit them. The page then takes those values and updates the MySQL database. Everything works perfectly except that when the user submits and the page goes to show the new updated variables, it still shows the old values. The user is forced refresh the page before the new variables show up. I thought that PHP was perhaps not deleting the variables, so I unset all stored variables after the script was over and it's still not working. I ever tried putting a sleep timer before the script started, and that didn't work either. I'd appreciate any suggestions. Here is my script just for reference:
<html>
<body>
<?php
$sql = "SELECT * FROM lease";
$result = mysql_query($sql);
?>
<form id="lease_update" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table>
<tr>
<th>Account</th>
<th>Car Lease</th>
<th>Radio Lease</th>
<th>Misc. Charges</th>
</tr>
<?php
while($rows = mysql_fetch_array($result)){
?>
<tr>
<td><input type="text" name="account[]" value="<?php echo $rows['accnt']; ?>" /></td>
<td><input type="int" name="car_lease[]" value="<?php echo $rows['car']; ?>" /></td>
<td><input type="int" name="radio_lease[]" value="<?php echo $rows['radio']; ?>" /> </td>
<td><input type="int" name="misc_lease[]" value="<?php echo $rows['misc']; ?>" /></td>
<input type="hidden" name="lease_ID[]" value="<?php echo $rows['ID']; ?>" />
</tr>
<?php
}
?>
</table>
<input type="submit" value="Update" name="lease_update" />
<?php
if(isset($_POST['lease_update'])){
$account = $_POST['account'];
$car_lease = $_POST['car_lease'];
$radio_lease = $_POST['radio_lease'];
$misc_lease = $_POST['misc_lease'];
$lease_ID = $_POST['lease_ID'];
//Get Array Lengths For Each Section
$A = count($lease_ID);
//Update Lease Information
$i = 0;
while($i < $A){
if(!mysql_query('UPDATE lease SET accnt = "' .$account[$i]. '", car = "' .$car_lease[$i]. '", radio = "' .$radio_lease[$i]. '", misc = "' .$misc_lease[$i]. '" WHERE ID = ' .$lease_ID[$i]))
die('Error: ' .mysql_error());
$i++;
}
unset($_POST);
unset($rows);
unset(result);
}
?>
</body>
</html>
You are displaying the data from the database before you update it.
It is normally good practice to do all your database connectivity at the top of the page, then display the results.
In your code (even if a user has submitted an update), you query the data, pull it from database and display it, then run the update with what the user submitted.
Changing your code to this should do the trick (Do read the note below though):
<html>
<body>
<?php
if(isset($_POST['lease_update'])){
$account = $_POST['account'];
$car_lease = $_POST['car_lease'];
$radio_lease = $_POST['radio_lease'];
$misc_lease = $_POST['misc_lease'];
$lease_ID = $_POST['lease_ID'];
//Get Array Lengths For Each Section
$A = count($lease_ID);
//Update Lease Information
$i = 0;
while($i < $A){
if(!mysql_query('UPDATE lease SET accnt = "' .$account[$i]. '", car = "' .$car_lease[$i]. '", radio = "' .$radio_lease[$i]. '", misc = "' .$misc_lease[$i]. '" WHERE ID = ' .$lease_ID[$i]))
die('Error: ' .mysql_error());
$i++;
}
unset($_POST);
unset($rows);
unset(result);
}
$sql = "SELECT * FROM lease";
$result = mysql_query($sql);
?>
<form id="lease_update" method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<table>
<tr>
<th>Account</th>
<th>Car Lease</th>
<th>Radio Lease</th>
<th>Misc. Charges</th>
</tr>
<?php
while($rows = mysql_fetch_array($result)){
?>
<tr>
<td><input type="text" name="account[]" value="<?php echo $rows['accnt']; ?>" /></td>
<td><input type="int" name="car_lease[]" value="<?php echo $rows['car']; ?>" /></td>
<td><input type="int" name="radio_lease[]" value="<?php echo $rows['radio']; ?>" /> </td>
<td><input type="int" name="misc_lease[]" value="<?php echo $rows['misc']; ?>" /></td>
<input type="hidden" name="lease_ID[]" value="<?php echo $rows['ID']; ?>" />
</tr>
<?php
}
?>
</table>
<input type="submit" value="Update" name="lease_update" />
</body>
</html>
Bad note - your code is wide open to injection attacks. You are using form data with no verification. That's a big red flag. Secondly, you are using deprecated mysql_* functions. Your code should be using mysqli_* functions or better yet move to PDO. It is much safer and you will be able to do a lot more with it.
Edit 2: The page IS being updated after the user submits the form, but the page you display to the user is querying the database before you update it - and using that to display the page to the user.

Validate Dynamic Dropdown With Ajax

I have a drop down menu of mobile brands. When a user selects a mobile brand a dynamic drop populates with the mobile model according to the mobile brand I want to validate that mobile model drop down for a blank select value. I am using ajax xmlhttp request for getting the mobile model drop down menu.
My entire code is:
Code for page with mobile brand drop down menu
<script type="text/javascript">
function validate() {
if (document.myform.step3_mobilebrand.value=="") {
document.getElementById("error1").innerHTML = (error1) ? "<img src='images/formerror.gif' height='15' width='18'>" : "";
document.myform.step3_mobilebrand.focus();
return false;
}
var myTextField = document.myform.getElementById('step3_mobilemodel').value;
if (myTextField == "") {
document.getElementById("error2").innerHTML = (error2)?"<img src='images/formerror.gif' height='15' width='18'>" : "";
document.myform.step3_mobilemodel.focus();
return false;
}
}
</script>
<?php
if (isset($_POST['submitted']) and $_POST['submitted']=="Continue") {
$mobilebrand1 = $_POST['step3_mobilebrand'];
$mobilemodel1 = $_POST['step3_mobilemodel'];
if ($mobilemodel1=="") {
echo "Please Select Mobile Model";
}
$connectiontype=$_POST['step3_connectiontype'];
$internet=$_POST['step3_internet'];
include("admin/config.php");
$sql="insert into member_detail (mobilebrand,mobilemodel,connection_type,internet) values('$mobilebrand1','$mobilemodel1','$connectiontype','$internet')";
mysql_query($sql);
}
?>
<script type="text/javascript">
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
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) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
<form name="myform" method="post" action="" onsubmit="return validate();">
<table>
<tr>
<td>Mobile Brand</td>
<td><?php
include ("admin/config.php");
echo "<select name='step3_mobilebrand' onchange='showUser(this.value)'><option value='' selected>Select Mobile Brand</option>";
$result = mysql_query ("select * from mobilebrand order by mobilebrand");
while ($adcom=mysql_fetch_array($result)) {
echo "<option value=\"".$adcom['id']."\">".htmlspecialchars($adcom['mobilebrand'])."</option>";
}
echo "</select>";?><span id="error1" style="color:red;"></span></td>
</tr>
</table>
<div id="txtHint"></div>
<table>
<tr>
<td>Connection Type</td>
<td><input type="radio" name="step3_connectiontype" value="PrePaid" checked="checked">Prepaid
<input type="radio" name="step3_connectiontype" value="PostPaid">Postpaid
<span id="error3" style="color:red;"></span>
</td>
</tr>
<tr>
<td>Have Internet On Mobile</td>
<td><input type="radio" name="step3_internet" value="Yes" checked="checked">Yes
<input type="radio" name="step3_internet" value="No">No
<span id="error4" style="color:red;"></span>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submitted" value="Continue"></td>
</tr>
</table>
</form>
and the code of getuser.php is
<table>
<tr>
<td>Mobile Model</td>
<td>
<?php
$q=$_GET["q"];
include("admin/config.php");
echo "<select name='step3_mobilemodel' id='step3_mobilemodel' ><option value=''>Select Mobile Model</option>";
$result = mysql_query ("select * from mobilemodel where brandcode='".$q."'");
while ($adcom=mysql_fetch_array($result)) {
echo "<option value=\"".$adcom['mobilemodel']."\">".htmlspecialchars($adcom['mobilemodel'])."</option>";
}
echo "</select>"; ?>
</td>
</tr>
</table>
The Output am getting is correct i just want to validate the mobile model drop down menu for blank select
For validating select you can do:
var e = document.getElementById("step3_mobilemodel");
var mobileVal = e.options[e.selectedIndex].value;
if(mobileVal == "") {
...//show your error here
}
Hope it helps
This is pretty much what Sudhir posted (+1 from me) but with an example in a fiddle: http://jsfiddle.net/5TYwH/1/ using the onchange event handler.
May be you can just add a php validation for $q.
<table>
<tr>
<td>Mobile Model</td>
<td>
<?php
$q=$_GET["q"];
echo "<select name='step3_mobilemodel' id='step3_mobilemodel'>"
if($q != ""){
include("admin/config.php");
echo "<option value=''>Select Mobile Model</option>";
$result = mysql_query ("select * from mobilemodel where brandcode='".$q."'");
while ($adcom=mysql_fetch_array($result)) {
echo "<option value=\"".$adcom['mobilemodel']."\">".htmlspecialchars($adcom['mobilemodel'])."</option>";
}}else{ echo "<option value=''>Please select a mobile first</option>";} echo "</select>";?></td>
</tr></table>

Getting values depending on the dropdown

I have a dropdown list for items. What I want to do is get the item quantity, remaining quantity and dispatched item values which depends on the value in the drop down.
I have this code :
<form method="post" action="restore_stocks.php">
<table>
<tr>
<td>Item Name:</td>
<td><select name="itemname">
<?php
$item="SELECT item_name FROM stocks";
$itemresult = #mysql_query($item)or die ("Error in query: $query. " . mysql_error());
while($row=#mysql_fetch_array($itemresult)){
echo "<OPTION VALUE=".$row['item_name'].">".$row['item_name']."</option>";
}
?>
</select></td></tr>
<tr>
<td>Item Quantity:</td>
<td><?php
$row = mysql_fetch_object($itemresult);
echo $row->item_quantity; ?></td></tr>
<tr>
<td>Remaining Quantity:</td>
<td><?php echo $row->rem_quantity; ?></td></tr>
<tr>
<td>Stocks Dispatched:</td>
<td><?php echo $row->stocks_dispatched; ?></td></tr>
<tr>
<td>Add Stocks:</td>
<td><input name="addstocks" type="text" size="25" maxlength="25" /></td></tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" id="Submit" value="Restore" /></td>
</tr>
</table>
</form>
I really don't know how to start the code because i'm new to this approach. If you can help me it's much appreciated. Thanks in advance.
This works: The jist is that the page uses ajax to call a script, which will deliver XML of the values you need, and will then populate those fields accordingly. :
<!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 Document</title>
</head>
<body>
<script>
function updateFields(itemname){
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 xmlDoc=xmlhttp.responseXML;
var iQdata=xmlDoc.documentElement.getElementsByTagName("ITEMQUANTITY");
var rQdata=xmlDoc.documentElement.getElementsByTagName("REMAININGQUANTITY");
var sDdata=xmlDoc.documentElement.getElementsByTagName("STOCKSDISPATCHED");
var iQ=iQdata[0].firstChild.nodeValue;
var rQ=rQdata[0].firstChild.nodeValue;
var sD=sDdata[0].firstChild.nodeValue;
document.getElementById("itemQuantity").innerHTML=iQ;
document.getElementById("remainingQuantity").innerHTML=rQ;
document.getElementById("stocksDispatched").innerHTML=sD;
}
}
xmlhttp.open("GET","quantity_script.php?itemname="+itemname,true);
xmlhttp.send();
}
</script>
<form method="post" action="restore_stocks.php">
<table>
<tr>
<td>Item Name:</td>
<td><select name="itemname" onchange="updateFields(this.value)">
<?php
$item="SELECT item_name FROM stocks";
$itemresult = #mysql_query($item)or die ("Error in query: $query. " .mysql_error());
while($row=#mysql_fetch_array($itemresult)){
echo "<OPTION VALUE=".$row['item_name'].">".$row['item_name']."</option>";
}
?>
</select></td></tr>
<tr>
<td>Item Quantity:</td>
<td><div id="itemQuantity"></div></td></tr>
<tr>
<td>Remaining Quantity:</td>
<td><div id="remainingQuantity"></div></td></tr>
<tr>
<td>Stocks Dispatched:</td>
<td><div id="stocksDispatched"></div></td></tr>
<tr>
<td>Add Stocks:</td>
<td><input name="addstocks" type="text" size="25" maxlength="25" /></td></tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" id="Submit" value="Restore" /></td>
</tr>
</table>
</form>
</body>
</html>
And then you'd also make a script on your site "quantity_script.php" that would be something like the following:
<?php
//include your DB connection info
$itemname=mysql_real_escape_string($_POST["itemname"]);
$item="SELECT ".$itemname." FROM stocks";
$itemresult = mysql_query($item);
$row=mysql_fetch_assoc($itemresult);
header('Content-type: text/xml');
echo "<ROOT>";
echo "<ITEMQUANTITY>".$row["item_quantity"]."</ITEMQUANTITY>";
echo "<REMAININGQUANTITY>".$row["rem_quantity"]."</REMAININGQUANTITY>";
echo "<STOCKSDISPATCHED>".$row["stocks_dispatched"]."</STOCKSDISPATCHED>";
echo "</ROOT>";
?>

Categories