PHP | $_POST failing to read value from a dropdown - php

I am new to php, so please do not mind if this is trivial.
I am trying to build a few web pages using php and mysql. The form contains a couple of drop downs and a text input. When the submit(POST) operation is performed, I am trying to insert the values in the mysql DB. Surprisingly I am able to get the values filled for a couple of variables ($doctor, $docFees), but one of them misses out ($spec) and hence a blank entry is getting created. Tried debugging, but an additional pair of fresh eyes can certainly help. Here is the code base that I am trying to work with..
if(isset($_POST['buy-submit']))
{
$pid = $_SESSION['pid'];
$username = $_SESSION['username'];
$email = $_SESSION['email'];
$fname = $_SESSION['fname'];
$lname = $_SESSION['lname'];
$gender = $_SESSION['gender'];
$contact = $_SESSION['contact'];
$doctor=$_POST['doctor'];
$spec=$_POST['spec'];
$email=$_SESSION['email'];
$docFees=$_POST['docFees'];
$appdate=$_POST['appdate'];
$apptime=$_POST['apptime'];
$cur_date = date("Y-m-d");
date_default_timezone_set('Asia/Kolkata');
$cur_time = date("H:i:s");
$apptime1 = strtotime($apptime);
$appdate1 = strtotime($appdate);
if($docFees>0){
//$check_query = mysqli_query($con,"select apptime from appointmenttb where doctor='$doctor' and appdate='$appdate' and apptime='$apptime'");
$check_query = mysqli_query($con,"select count(*) from med_inv where med_name='$spec' and quantity>'$docFees'");
if(mysqli_num_rows($check_query)==1){
$query=mysqli_query($con,"insert into med_sale(med_name,quantity) values('$med_name','$docFees')");
if($query)
{
echo "<script>alert('Your order is successfully placed');</script>";
}
else{
echo "<script>alert('Unable to process your request. Please try again!');</script>";
}
}
else{
echo "<script>alert($doctor);</script>";
echo "<script>alert($docFees);</script>";
echo "<script>alert('Requested Quantity Not available in STOCK!! SORRY! ');</script>";
}
}
else{
echo "<script>alert('Invlaid Quantity specified!!');</script>";
}
}
<div class="tab-pane fade" id="list-home" role="tabpanel" aria-labelledby="list-home-list">
<div class="container-fluid">
<div class="card">
<div class="card-body">
<center><h4>Order a Medicine</h4></center><br>
<form class="form-group" method="post" action="admin-panel.php">
<div class="row">
<div class="col-md-4">
<label for="spec">Medicine Name :</label>
</div>
<div class="col-md-8">
<select name="spec" class="form-control" id="spec" required="required">
<option value="" </option>
<?php
display_meds();
?>
</select>
</div>
<br><br>
<script>
document.getElementById('spec').onchange = function foo() {
let spec = this.value;
console.log(spec)
document.getElementbyID('doctor').value='';
let docs = [...document.getElementById('doctor').options];
docs.forEach((el, ind, arr)=>{
arr[ind].setAttribute("style","");
if (el.getAttribute("data-spec") != spec ) {
arr[ind].setAttribute("style","display: none");
}
});
};
</script>
<div class="col-md-4"><label for="doctor">Price:</label></div>
<div class="col-md-8">
<select name="doctor" class="form-control" id="doctor" required="required">
<option value="" disabled selected></option>
<?php display_xdocs(); ?>
</select>
</div><br/><br/>
<script>
document.getElementById('doctor').onchange = function updateFees(e) {
var selection = document.querySelector(`[value=${this.value}]`).getAttribute('data-value');
document.getElementById('docFees').value = selection;
};
</script>
<div class="col-md-4"><label for="consultancyfees">
Quantity
</label></div>
<div class="col-md-8">
<!-- <div id="docFees">Select a doctor</div> -->
<input class="form-control" type="text" name="docFees" id="docFees" required="required"/>
</div><br><br>
<div class="col-md-4">
<input type="submit" name="buy-submit" value="Purchase Medicine" class="btn btn-primary" id="inputbtn">
</div>
<div class="col-md-8"></div>
</div>
</form>
</div>
</div>
</div><br>
</div>
Functions used
function display_meds() {
global $con;
$query="select distinct(med_name) from med_inv";
$result=mysqli_query($con,$query);
while($row=mysqli_fetch_array($result))
{
$med_name=$row['med_name'];
echo '<option data-value="'.$med_name.'">'.$med_name.'</option>';
}
}
function display_xdocs()
{
global $con;
$query = "select * from med_inv";
$result = mysqli_query($con,$query);
while( $row = mysqli_fetch_array($result) )
{
$username = $row['mrp'];
$price = $row['mrp'];
$spec = $row['med_name'];
echo '<option value="' .$username. '" data-value="'.$price.'" data-spec="'.$spec.'">'.$username.'</option>';
}
}
Values inserted into the table med_sale. First entry was manual for test purpose. So clearly $spec value is not being read from the POST method.
mysql> select * from med_sale;
+----------+----------+
| med_name | quantity |
+----------+----------+
| test | 5 |
| | 5 |
| | 7 |
| | 700 |
| | 4 |
| | 33 |
+----------+----------+
6 rows in set (0.00 sec)

Two problems.
Firstly invalid HTML, missing >:
<option value="" </option>
Secondly, in your display_meds function data-value should be simply value, like so:
echo '<option value="'.$med_name.'">'.$med_name.'</option>';

Related

Update database based on form input

I am trying to perform an update on a database based on the input of a form but facing an issue. I have tried the below but it is not executing the command on the database. It needs to read in a value for decision and carry out a query based on the decision.Can anyone spot the issue here ?
html form code :
<center><div class="container">
<form action="update.php" onsubmit="return confirm('Are you sure you wish to update ?');">
<div class="row">
<div class="col-25">
<label for="decision">Would you like to add or subtract from current quantity?</label>
</div>
<div class="col-75">
<select id="decision" name="decision">
<option value="add">Add</option>
<option value="subtract">Subtract</option>
</select>
</div>
</div>
<br>
<div class="row">
<div class="col-25">
<label for="License Group ID">License Group ID</label>
</div>
<div class="col-75">
<input type="number" name="LicenseGroupID" placeholder="LicenseGroupID">
</div>
</div>
<br>
<div class="row">
<div class="col-25">
<label for="Quantity">Quantity</label>
</div>
<div class="col-75">
<input type="number" name="Quantity" placeholder="Quantity">
</div>
</div>
<br>
<div class="row">
<input type="submit" value="Update">
</div>
update.php
<html>
<?php
$serverName = "tcp:xxx,1433";
$options = array( "UID" => "aalicensemanager", "PWD" => "xxx", "Database" => "AALicenseManager");
$conn = sqlsrv_connect($serverName, $options);
if( $conn === false )
{
echo "Could not connect.\n";
die( print_r( sqlsrv_errors(), true));
}
$decision = $_POST['decision'];
$LicenseGroupID = $_POST['LicenseGroupID'];
$Quantity = $_POST['Quantity'];
$query = " CASE WHEN $decision = 'add'
THEN
UPDATE dbo.[tbl_license_group]
SET Quantity = Quantity + '$Quantity'
WHERE License_Group_ID = '$LicenseGroupID'
ELSE WHEN $decision = 'subtract'
THEN
UPDATE dbo.[tbl_license_group]
SET Quantity = Quantity - '$Quantity'
WHERE License_Group_ID = '$LicenseGroupID'" ;
$params1 = array($decision,$LicenseGroupID,$Quantity);
$result = sqlsrv_query($conn,$query,$params1);
sqlsrv_close($conn);
?>
</html>
Your update statement should look something like....
UPDATE dbo.[tbl_license_group]
SET Quantity = CASE
WHEN $decision = 'add' THEN Quantity + '$Quantity'
WHEN $decision = 'subtract' THEN Quantity - '$Quantity'
END
WHERE License_Group_ID = '$LicenseGroupID'
You need to put your case statement inside your update statement not update statement inside your case statement.

Changing form fields with ajax but field values not passing on submit

I have a standard form with a drop down list of customers, using ajax when a customer is selected it calls the load-customers.php page and changes the form fields entirely based on customer_id whilst filling it with the relevant information.
One of these fields is another drop drown called address_id which again allows the user to select from multiple addresses already defined for the selected customer.
The issue is, address_id is not being passed to $_POST on submit, to be fair none of the other fields are either... but the other fields are just placeholders and i only care about the customer_id and address_id.
How do i get around this? This is the only bit of ajax I've ever used.
ajax:
function getCustomer(val) {
$.ajax({
type: "POST",
url: "load-customers.php",
data:'id='+val,
success: function(data){
$("#customer").html(data);
}
});
}
customer:
<div class='form-group row'>
<label class='col-md-4 control-label'>Quick Select</label>
<div class='col-md-8 selectContainer'>
<div class='input-group'>
<span class='input-group-addon'><i class=''></i></span>
<select name='Customer_ID' class='form-control selectpicker' id='Customer_ID'
onChange="getCustomer(this.value);">
<option value='0'>Please create a new Customer</option>
<?php
$sell_type = "Trade";
$getcustomer = $conn->prepare("SELECT * FROM customers WHERE type = :type");
$getcustomer->bindParam(':type', $sell_type);
$getcustomer->execute();
foreach ($getcustomer->fetchAll(PDO::FETCH_ASSOC) as $row) {
$customer_id = $row['id'];
$customer_name = $row['name'];
$customer_company = $row['company'];
if (!empty($customer_company)) {
$customer = $customer_company;
} else {
$customer = $customer_companyname;
}
echo "<option value='$customer_id'>$customer</option> ";
}
?>
</select>
</div>
</div>
</div>
<div id='address'>
// address results go here
</div>
address:
<div class='form-group row'>
<label class='col-md-4 control-label'>Postcode</label>
<div class='col-md-8 selectContainer'>
<div class='input-group'>
<span class='input-group-addon'><i class=''></i></span>
<select id='address_id' class='form-control selectpicker' name='address_id' >
";
$getaddresses = $conn->prepare("SELECT * FROM addresses WHERE customer_id = :id");
$getaddresses->bindParam(':id', $customer_id);
$getaddresses->execute();
foreach ($getaddresses->fetchAll(PDO::FETCH_ASSOC) as $row) {
$address_id = $row['id'];
$postcode = $row['postcode'];
$areacode = $row['areacode'];
echo "
<option value='$address_id'>$postcode</option>
";
}
echo "
</select>
</div>
</div>
</div>
The form itself is quite large but the header is:
<form class="form-horizontal justify-content-center" action="new.php" method="post" id="form">
and submitted with:
<button type="submit" class="btn btn-primary mb-2">Submit</button>

Fetching data on textarea & dropdown doesn't work

I'm trying to do an update page, the data that I'm fetching are input texts, dates, dropdowns and a textarea.
The data on input texts & date works completely fine however, the data on my dropdowns and textarea wont appear.
I still can update it, the only problem here is it just won't appear. So I'm hoping if anybody can help me and see what I missed in my coding.
How my form looks like:
Solution:
I've found the solution to this question and below is my new html coding. There a few php coding that I edited at the dropdown and the dates.
Updated html code:
php code that are outside from my html:
<?php
session_start();
require('db.php');
include("auth.php");
$noID=$_REQUEST['noID'];
$query = "SELECT * from daftartempah where noID='".$noID."'";
$result = mysqli_query($con, $query) or die ( mysqli_error());
$row = mysqli_fetch_assoc($result);
?>
php code that are inside my html:
<?php
$status = "";
if(isset($_POST['new']) && $_POST['new']==1)
{
$noID=$_REQUEST['noID'];
$trn_date = date("Y-m-d H:i:s");
$pemohon =$_REQUEST['pemohon'];
$trkhMula = $_REQUEST['trkhMula'];
$trkhAkhir =$_REQUEST['trkhAkhir'];
$n_program = $_REQUEST['n_program'];
$lokasi =$_REQUEST['lokasi'];
$n_anjuran = $_REQUEST['n_anjuran'];
$catatan = $_REQUEST['catatan'];
$status_hr = $_REQUEST['status_hr'];
$submittedby = $_SESSION["username"];
$update="update daftartempah set trn_date='".$trn_date."', pemohon='".$pemohon."', trkhMula='".$trkhMula."', trkhAkhir='".$trkhAkhir."', n_program='".$n_program."', lokasi='".$lokasi."', n_anjuran='".$n_anjuran."', catatan='".$catatan."', status_hr='".$status_hr."', submittedby='".$submittedby."' where noID='".$noID."'";
mysqli_query($con, $update) or die(mysqli_error());
$status = "Record Updated Successfully. </br></br>
<a href='Page8.php'>View Updated Record</a>";
echo '<p style="color:#FF0000;">'.$status.'</p>';
}else {
?>
Dropdowns:
<div class="form-group row text-left">
<label for="example-text-input" class="col-3 col-form-label"><b>Dept/Kelab/Anjuran: </b></label>
<div class="col-8">
<select class="form-control" name="n_anjuran" id="namaAnjuran">
<option selected name="" value="<?php echo $row['n_anjuran'];?>"><?php echo $row['n_anjuran'];?></option>
<?php
$sql = mysqli_query($con, "SELECT kd_dept, desc_dept From koddept");
$rows = mysqli_num_rows($sql);
while ($rows = mysqli_fetch_array($sql)){
echo "<option value='". $rows['kd_dept'] ."'>" .$rows['desc_dept'] ."</option>" ;
}
?>
</select>
</div>
</div>
Textarea:
<div class="form-group row text-left">
<label for="exampleTextarea" class="col-3 col-form-label"><b>Catatan: </b></label>
<div class="col-8">
<textarea class="form-control" rows="3" name="catatan" required><?php echo $row['catatan'];?></textarea>
</div>
</div>
My new form:
All questions are welcome, feel free to comment and ask, I'll try to help.

Unable to update database from form retrieved by SELECT OPTION

I couldn't figure out what is the problem with $updateApproval statement. Everything is fine and the $_POST is able to retrieve the data from the form. SQL statement works well on phpMyAdmin when I run it , substituting the variables so there should not be any mistakes.
Am I conflicting without knowing or there are some other reasons that my update statement is not working? Tried switching here and there but it just kept quiet and no slightest error is out. I provide you the information you need and sorry if it is tedious. Any help is greatly appreciated. Thank you.
This is my database:
Consent Table
consent
-----------------------------------------------------------------------------------------
consent_id | staff_id | approval_id | type_of_leave | consent_date_from | consent_date_to
Leave Type Table
leavetype
----------------------------
type_of_leave | leave_type |
Staff Table
staff
------------------------------------------------------------------
staff_id | role_id | staff_name | gender | staff_email | password |
Staff Leave table
staffleave
----------------------------------------------------------------------
leave_log | staff_id | annual_leave | sick_leave .....//other leaves and so on
The form is over here. I have actually put a select option into a form, thus there's the <td> <tr> tag.
<td>
<div class="form-group">
<form action="doApproval.php" method="post" name="register">
<input hidden name="getStaffId" value="<?php echo $staffId ?>" >
<input hidden name="getConsentId" value="<?php echo $consentId ?>" >
<input hidden name="getLeaveId" value="<?php echo $leaveId ?>" >
<div class="form-group">
<select class="form-control" onchange="this.form.submit()" id="select" name="getConsentChange">
<option value="1" <?php if ($getCurrentStatus == 1) echo "selected"; ?>>Approve</option>
<option value="2" <?php if ($getCurrentStatus == 2) echo "selected"; ?>>Reject</option>
<option <?php if ($getCurrentStatus == 3) echo "selected"; ?>>Pending</option>
</select>
</div>
<noscript><input type="submit" value="Submit"></noscript>
</form>
</div>
</td>
The POST will be over here. The query that saves the number of days staff take works well, but not the status of their leave.
$staffId = $_POST['getStaffId'];
$consentId = $_POST['getConsentId'];
$getConsent = $_POST['getConsentChange'];
$getLeaveId = $_POST['getLeaveId'];
$updateApproval = "UPDATE consent SET approval_id = $getConsent WHERE consent.staff_id = '$staffId' AND consent.consent_id = $getConsent"; //Update statement that is not working
$leaveCheckpoint = "SELECT * FROM consent, staffleave, staff WHERE staffleave.staff_id = staff.staff_id
AND staff.staff_id = consent.staff_id AND consent.consent_id = '$consentId'";
$checkpointQuery = (mysqli_query($link, $leaveCheckpoint)) or die("Retrieve checkpoint error " . mysqli_error($link));
if ($checkLeave = mysqli_fetch_array($checkpointQuery)) {
if ($checkLeave['staff_id'] = '$staffId' && $checkLeave['consent_id'] = '$consentId') {
//retrieving the number of leaves staff have took
if ($getLeaveId == 1 && $getConsent == 1) {
$updatedLeave1 = $chkAnnual + $dateDiff;
$recordLeave = "UPDATE staffleave SET annual_leave = '$updatedLeave1' WHERE staff_id = '$staffId'";
} else if ($getLeaveId == 2 && $getConsent == 1) {
$updatedLeave2 = $chkSick + $dateDiff;
$recordLeave = "UPDATE staffleave SET sick_leave = '$updatedLeave2' WHERE staff_id = '$staffId'";
} else if ......// so on when they meet the condition, it works fine and able to insert.
else {
?>
<script type="text/javascript">
alert("No data was updated in the process")
window.location = "manageStaffLeave.php";
</script>
}
<?php
}
$successConsent = mysqli_query($link, $recordLeave) or die("Insert Leave Date Error " . mysqli_error($link));
}
$approvalUpdate = (mysqli_query($link, $updateApproval)) or die("Update error " . mysqli_error($link));
mysqli_close($link);
?>
<!DOCTYPE html>
<body>
if ($approvalUpdate && $successConsent) {
?>
<script type="text/javascript">
window.location = "manageStaffLeave.php";
</script>
<?php
}
?>
</body>
I think you missed out ';'
<input hidden name="getStaffId" value="<?php echo $staffId; ?>" >
<input hidden name="getConsentId" value="<?php echo $consentId; ?>" >
<input hidden name="getLeaveId" value="<?php echo $leaveId; ?>" >
You are making a basic mistake :
$checkLeave['staff_id'] = '$staffId' && $checkLeave['consent_id'] = '$consentId
Here you are affecting the strings '$staffId' to the array $checkLeave['staff_id'] and $consentId to $checkLeave['consent_id']
Remove quote and and an equal for comparison :
$checkLeave['staff_id'] == $staffId && $checkLeave['consent_id'] == $consentId

Input text value based on select option value loaded dynamically from sql db

I have a form that has a select field that loads the options dynamically from a db result query. Here is what the code looks like. See the description text input afterwards? I need the code to return the description of the item selected under productID. How do I go about this? Thanks very much for all replies.
<div class="row-fluid">
<div class="span3">
<label>SKU</label>
<?php echo '<select name="ITEM" id="user" class="textfield1">';
while($res= mysql_fetch_assoc($sql))
{
echo '<option value="'.$res['productID'].'">';
echo $res['SKU'] ;
echo'</option>';
}
echo'</select>';
?>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<label>Description</label>
<input type="text" name="description" value=""/>
</div>
</div>
You can do this in 2 ways:
First way is by redirecting the page having a $_GET parameter which will contain the product id:
<div class="row-fluid">
<div class="span3">
<label>SKU</label>
<?php echo '<select name="ITEM" id="user" class="textfield1"
onchange="document.location=\'my-page.php?pid=\' + this.value">';
while($res= mysql_fetch_assoc($sql))
{
echo '<option value="'.$res['productID'].'"';
// LATER EDIT
if(isset($_GET['pid']) && $_GET['pid'] == $res['productID'])
echo 'selected="selected"';
// END LATER EDIT
echo '>';
echo $res['SKU'] ;
echo'</option>';
}
echo'</select>';
?>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<label>Description</label>
<?php
if(isset($_GET['pid']) && is_numeric($_GET['pid'])) {
$sql = mysql_query("SELECT description
FROM products
WHERE product_id='" . mysql_real_escape_string($_GET['pid']) . "'");
$row = mysql_fetch_assoc($sql);
}
?>
<input type="text" name="description" value="<?=$row['description']?>"/>
</div>
</div>
Second way is to have an ajax call and fill description input dynamically, without refresing the page
// this is the JS code
$(document).ready(function(){
$('#user').change(function(){
$.POST("my-ajax-call-page.php",
{pid: $("#user").val()},
function(data){
$('input[name="description"]').val(data.description);
}, "json");
});
});
and your my-ajax-call-page.php should be like this:
<?php
include("mysql-connection.php");
$sql = mysql_query("SELECT description
FROM products
WHERE product_id='" . mysql_real_escape_string($_POST['pid']) . "'");
$row = mysql_fetch_assoc($sql);
echo json_encode("description" => $row['description']);
?>
You will find many examples and documentation for using jQuery library on jQuery library website
<div class="row-fluid">
<div class="span3">
<label>SKU</label>
<?php echo '<select name="ITEM" id="user" class="textfield1" onchange="showDesc()">';
$desHTML = "";
echo "<option value='0'>Please select</option>"
while($res= mysql_fetch_assoc($sql))
{
echo '<option value="'.$res['productID'].'">';
echo $res["SKU"] ;
echo'</option>';
$desHTML .="<div class'descBox' id='".$res['productID']."' style='display:none'>".$res['description']."</div>";
}
echo'</select>';
?>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<label>Description</label>
<?php echo $desHTML; ?>
</div>
</div>
Now create one js function and call on onchange of select box.
Js function Hint:
$(".descBox").hide();
$("#"+selectedItemValue).show();
Let me know if you need any help for JS function.
You haven't shown us your SQL query, but I assume that you have a column named description and you are selecting this column in your query too.
So then, you can use jQuery to insert description of selected item to input
<div class="row-fluid">
<div class="span3">
<label>SKU</label>
<?php echo '<select name="ITEM" id="user" class="textfield1">';
$js_array = array(); // This variable will contain your Javascript array with descriptions
while($res= mysql_fetch_assoc($sql))
{
echo '<option value="'.$res['productID'].'">';
echo $res['SKU'] ;
echo'</option>';
// Fill your array with descriptions; ID of item will be the index of array
$js_array[$res['productID']] = $res['description'];
}
echo'</select>';
?>
<script>
var description;
<?php
foreach($js_array as $description => $id)
{
echo("description['".$id."'] = '".$description."';\n");
}
?>
$(document).ready(function(){
$('#user').change(function(){
$("#description").val(description[$('#user').val()]);
})
});
</script>
</div>
</div>
<div class="row-fluid">
<div class="span3">
<label>Description</label>
<input type="text" name="description" id="description" value=""/>
</div>
</div>
Be sure to not forget to add id attribute to your input type="text"

Categories