How to enable disable option value in select based on condition PHP - javascript

After user select location,in the next select option which is select car, will show list of car in selected location..The list of car retrieved direct from database..So i need to display all the car list in that area and need to disable enable the car list according the condition which is if the car id is not available the option value will disabled..and the option value become enable if car id is available..
<?php
$car = "SELECT *,location_master.location_id , location_master.location_name,
appcarinfo.loc_id_ext, appcarinfo.location ,appcarinfo.model ,appcarinfo.noplat FROM location_master
INNER JOIN appcarinfo ON
appcarinfo.lat = location_master.gmaplat
AND
appcarinfo.lon = location_master.gmaplng
where appcarinfo.model='".$fetchres['idmodel']."' ";
$qcar = mysqli_query($conn, $car);
?>
<option disabled value="" selected hidden>Please Select Car</option>
<?php
while ($showcar= mysqli_fetch_array($qcar))
{
if ($showcar['car_id']=="Available")
{
?>
<option class="<?php echo $showcar['lon']; ?>" value="<?php echo $showcar['car_id']; ?>" enabled> <?php echo $fetchres['maker'].' '.$fetchres['model_name'].'-'.$showcar['noplat'].' ' .$showcar['location_name']; ?></option>
<?php
}
else
?> <option class="<?php echo $showcar['lon']; ?>" value="<?php echo $showcar['car_id']; ?>" disabled> <?php echo $fetchres['maker'].' '.$fetchres['model_name'].'-'.$showcar['noplat'].' ' .$showcar['location_name']; ?></option>
<?php
}
?>
</select>
SELECT OPTION
I'm also new to AJAX..how to pass data and retrieve it back to select option
//check availability car
function check_availability()
{
//id from form
var reservation1 = document.getElementById("reservation");
var pickup_date = document.getElementById("pickup_date").value;
var return_date = document.getElementById("return_date").value;
var pickup_time = document.getElementById("pickup_time").value;
var return_time = document.getElementById("return_time").value;
var carID= document.getElementById("carID").value;
$.ajax({
type : "POST",
url : "function/check_car_availability.php",
data : {
pickup_date : pickup_date,
return_date : return_date,
pickup_time : pickup_time,
return_time : return_time,
carID : carID,
},
dataType : "JSON",
success : function(data) {
$('#edt_pickup').val(data.edt_pickup);
$('#edt_return').val(data.edt_return);
$('#msgCheck').html(data.msgCheck);
$('#btn_proceed').html(data.btn_proceed);
}
});
}
check_car_availability.php
<?php
if ($_POST['pickup_date'])
{
$pickup_date = $_POST['pickup_date'];
$return_date = $_POST['return_date'];
$pickup_time = $_POST['pickup_time'];
$return_time = $_POST['return_time'];
$car_id = $_POST['car_id'];
$owner_id = $_POST['owner_id'];
//convert normal date to epoch
$pickup_date1 = explode("/",$pickup_date);
$return_date1 = explode("/",$return_date);
$pickup_time1 = explode(":",$pickup_time);
$return_time1 = explode(":",$return_time);
//hour, minute, second, month, day, year
$edt_pickup = mktime($pickup_time1[0],$pickup_time1[1],0,$pickup_date1[1],$pickup_date1[0],$pickup_date1[2]);
$edt_return = mktime($return_time1[0],$return_time1[1],0,$return_date1[1],$return_date1[0],$return_date1[2]);
//convert from d/m/Y to Y-m-d
$pickup_date_2 = $pickup_date1[2]."-".$pickup_date1[1]."-".$pickup_date1[0];
$return_date_2 = $return_date1[2]."-".$return_date1[1]."-".$return_date1[0];
//keluarkan tarikh yg customer pilih ada tak dlm booking master
$chkBooked = mysqli_query($conn, "SELECT count(car_id) AS countid FROM appbooking WHERE
((start_rent >= '$edt_pickup' AND end_rent <= '$edt_return')
OR (((start_rent <= '$edt_pickup' AND end_rent >= '$edt_return')))
OR (((end_rent >= '$edt_pickup' AND end_rent <= '$edt_return')))
OR (((start_rent >= '$edt_pickup' AND start_rent <= '$edt_return')))) AND car_id = '$car_id' AND status !='0'");
$fetchBooked = mysqli_fetch_array($chkBooked);
if($fetchBooked['countid'] != 0) //kalau ada show not available
{
$availability = "Not Available";
$available_count = 0;
} else //kalau tak de show available
{
$availability = "Available";
$available_count = 1;
}
//keluarkan car details
$carDetails = mysqli_query($conn, "SELECT * FROM appcarinfo WHERE car_id = '$car_id'");
$fetchchkowner = mysqli_fetch_array($carDetails);
//kalau manual availability check ada tak date dlm range yg owner dah set
$sql = mysqli_query($conn, "SELECT count(car_availability.availability_id) AS cntAvail FROM appcarinfo INNER JOIN car_availability ON car_availability.car_id = appcarinfo.car_id WHERE appcarinfo.car_id = '$car_id' AND car_availability.start_available <= '$edt_pickup' AND car_availability.end_available >= '$edt_return'");
$fetch = mysqli_fetch_array($sql);
if ($fetchchkowner['custom_availability'] == 1) //if owner set manual availability
{
if ($fetch['cntAvail'] > 0) //kalau ada
{
$avail = 1;
} else //kalau tak de
{
$avail = 0;
}
} else //if owner set auto availability
{
$avail = 1;
}
//check if this is klezcar car
if($fetchchkowner["owner_id"] == "0")
{
$klezcar_loc_id = $fetchchkowner["loc_id_ext"];
//check availability for blocked date klezcar
$sqlBlock = "SELECT * FROM `blocked_date_klezcar` where (
('".$pickup_date_2."' > startdate and '".$pickup_date_2."' < enddate)
or ('".$return_date_2."' > startdate and '".$return_date_2."' < enddate)
or ('".$pickup_date_2."' = startdate)
or ('".$return_date_2."' = enddate)
or ('".$return_date_2."' = startdate)
or ('".$return_date_2."' = enddate)
) and (location=0 or location=".$klezcar_loc_id.") order by location desc limit 1";
$queryBlock = mysqli_query($conn,$sqlBlock);
if(mysqli_num_rows($queryBlock) > 0)
{
$resBlock = mysqli_fetch_object($queryBlock);
$avail = 0;
$klezcar_blocked = 1;
$klezcar_blocked_reason = $resBlock->reason;
}
else
{
$klezcar_blocked = 0;
}
}
//calculation price rate
include 'calculation_price/calculationprice.php';
$encry = md5($edt_pickup.$edt_return.$total_pay.$total_rate.floor($day).$bhourplus.$car_id.$owner_id.$secretAuth);
//combine appbooking & car availability variable
if ($avail == 1 && $available_count == 1)
{
$availStatus = "<div class='alert alert-success'>You are good, car available.<br>Rental Price : Total <span style='font-size:20px; font-weight: bold;'>".number_format($total_pay,2)."</span> for ".floor($day)." day(s) ".$bhourplus." hour(s)</div>";
$btn_proceed = "<a href='confirmbooking.php?pickupdate=".$edt_pickup."&returndate=".$edt_return."&totalpay=".$total_pay."&totalrate=".$total_rate."&bookday=".floor($day)."&bookhour=".$bhourplus."&carid=".$car_id."&ownerid=".$owner_id."&encry=".$encry."' class='btn btn-primary'>Proceed</a>";
} else
{
$availStatus = "<div class='alert alert-danger'>We are sorry, car not available. Please refer Available & Not available date table.</div>";
$btn_proceed = "";
if($klezcar_blocked === 1)
{
$availStatus = "<div class='alert alert-danger'>".$klezcar_blocked_reason."</div>";
$btn_proceed = "";
}
}
/* *** SPECIAL FOR RAYA 2019 *** */
$start_blocked_date = "2019-06-04";
$end_blocked_date = "2019-06-09";
if( ($pickup_date_2 >= $start_blocked_date && $pickup_date_2 <= $end_blocked_date)
|| ($return_date_2 >= $start_blocked_date && $return_date_2 <= $end_blocked_date)
|| ($pickup_date_2 == $start_blocked_date)
|| ($return_date_2 == $end_blocked_date)
|| ($return_date_2 == $start_blocked_date)
|| ($return_date_2 == $end_blocked_date))
{
$availStatus = "<div class='alert alert-danger'>The date has been marked as Hari Raya Aidlifitri holiday session. We accept minimum rental of 7 days and above only. Please re-select date at least 3/6/2019 - 10/6/2019.</div>";
$btn_proceed = "";
}
/* *** SPECIAL FOR RAYA 2019 *** */
//return value
$data['edt_pickup'] = $edt_pickup;
$data['edt_return'] = $edt_return;
$data['msgCheck'] = $availStatus;
$data['btn_proceed'] = $btn_proceed;
$data['total_rate'] = $total_rate;
$data['total_pay'] = $total_pay;
$data['no_day_booking'] = floor($day);
$data['no_hour_booking'] = $bhourplus;
echo json_encode($data);
}
?>

Related

How to select values from more tasks assigned to same project

I have an app where I can create a Project and, inside the Project, I can create Tasks. For every Task, I can add a percent and calculate a price (example picture 1).
Then I have a report page where I want to calculate all the prices from all of the Tasks of same project (example picture 2). Now I used a code with logic that works for other sums on same project (example picture 3), but when I use this code for the percent sum of all tasks its not working properly (example picture 4, in this picture I put to display the array not the sum)
picture 1:
picture 2 (but here the problem is that just the first array is corrent the other are not):
picture 3 (same code - works good):
Code:
if($projectTaskIds && count($projectTaskIds)){
$realTime = 0;
$estimateCost = 0;
$itemName = '';
$realCost = 0;
$realCostArr = array();
$totalCalEArr = array();
foreach ($projectTaskIds as $key => $projectTaskId) {
// echo $projectTaskId['id'];
// echo "<br>";
$calB = 0;
$calC = 0;
$itemtotal = 0;
$items = get_items_by_type('task', $projectTaskId['id']);
if($items && count($items) > 0){
$itemNo = 1;
foreach ($items as $key => $item) {
$itemtotal += ($item["rate"]*$item["qty"]);
$itemName .= '<div>'.$itemNo.'.'.$item["description"].' <b>('.round($item["qty"]).')</b>'.'</div>';
$itemNo++;
}
}
// =============== the code that doesn't work ============
$calF = get_task_user_hourly_rate($assignees_id[0]); // hourly_rate
$calG = get_task_custom_billable_amount($aRow['id']);
if($aRow['task_item_percentage']){
$calE = ((round($itemtotal + ((($calF * $aRow['task_duration'] / 60))))*($aRow['task_item_percentage']/100)))+(round($itemtotal + (($calF * $aRow['task_duration'] / 60)))); // additionalPriceTotal
}
else {
$calE = ($itemtotal+$aRow['task_item_manual_total_price']-$itemtotal);
}
$totalCalE = $calE;
$totalCalEArr[] = $totalCalE;
if($totalCalEArr && count($totalCalEArr) > 0){
$totalsCalEaMount = 0;
foreach ($totalCalEArr as $key => $totalvalue) {
$totalsCalEaMount += $totalvalue;
}
}
// =============== the code that doesnt work ============
$realTime += get_calc_task_real_logged_time($projectTaskId['id']);
$calB = get_task_custom_billable_amount($projectTaskId['id']);
if($aRow['task_item_percentage']){
$calC = ((round($itemtotal + ((($calF * $aRow['task_duration'] / 60))))*($aRow['task_item_percentage']/100)))+(round($itemtotal + (($calF * $aRow['task_duration'] / 60)))); // additionalPriceTotal
} else {
$calC = ($itemtotal+$aRow['task_item_manual_total_price']-$itemtotal);
}
$estimateCost += round($itemtotal+($calA * $aRow['task_duration'] / 60));
$realCost = round($itemtotal+$calB);
// if($calC = 0){ $realCost = round($itemtotal+$calB);} else { $realCost = round($itemtotal+$calB+$calC);
// }
$realCostArr[] = $realCost;
}
if($realCostArr && count($realCostArr) > 0){
$realCostAmount = 0;
foreach ($realCostArr as $key => $reslcostvalue) {
$realCostAmount += $reslcostvalue;
}
}
}
$outputName = '';
$relName = '';
$row[] = $loop;
if ($aRow['rel_name']) {
$relName = task_rel_name($aRow['rel_name'], $aRow['rel_id'], $aRow['rel_type']);
$link = task_rel_link($aRow['rel_id'], $aRow['rel_type']);
$relName = '<span class="hide"> - </span><a class="text-muted task-table-related" data-toggle="tooltip" title="' . _l('task_related_to') . '" href="' . $link . '">' . $relName . '</a>';
}
$row[] = $relName;
$row[] = count($projectTaskIds);
$row[] = $itemName;
$row[] = $aRow['task_duration']*count($projectTaskIds);
$row[] = round($realTime/60);
$row[] = round($estimateCost);
$row[] = round($realCostAmount);
$row[] = '';
$row[] = $totalCalEArr; // display as array or $row[] = $totalsCalEaMount; to display as a sum
$output['aaData'][] = $row;
$loop++;
}

Multiple fields with the same name in AJAX and PHP

Everyone.
I got some good help a couple of days ago, so I'm hoping that someone can show me where I'm going wrong here. Basically, what I'm trying to do is update a MySQL database in the background when a user clicks a button. The form is a series of records, and the records have common field names (ID, DSA_Number, Manager_Review, etc.) Right now, the code doesn't even seem to return success or failure messages.
Here's the script on the main page:
<script>
$(document).ready(function(){
$("#button").click(function(){
var DDD_Number=$("#DDD_Number").val();
var Manager_Review=$("#Manager_Review").val();
var RID=$("#RID").val();
var Services=$("Services").val();
var Dues_List=$("Dues_List").val();
var ID=$("ID").val();
var myrid=$("myrid").val();
var Manager_Comments=$("Manager_Comments").val();
var President_Comments=$("President_Comments").val();
var dataTosend='?DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review+'&RID='+RID+'&Services='+Services+'&Dues_List='+Dues_List+'&Manager_Comments='+Manager_Comments+'&President_Comments='+President_Comments;
$.ajax({
type: "GET",
url:'baseupdater-test.php' + dataTosend,
data:dataTosend,
async: true,
success:function(data){
document.getElementById('stuffhere').innerHTML.text = "Success.";
document.getElementById('stuffhere').innerHTML.text = data;
},
error: function(data){
document.getElementById('stuffhere').innerHTML.text = "Failure.";
}
});
});
</script>
Here's the code that draws the rows on the table:
<?php
/* This code writes the rows in the table for baserecord.php */
$n = 0;
$o = $n + 1;
$firstday = date('m/1/Y');
if(isset($_GET['MR'])) // If $_GET['MR'] is set ...
{
$MR = $_GET['MR']; // Set the variables.
$PR = $Pres_Rev;
}
else // If not, select the maximum (latest) Manager Review Date.
{
$getmr = "select max(STR_TO_DATE(Manager_Review_Date, '%m/%d/%Y')) as Manager_Review_Date,
President_Review_Date from clientdb.MRS2_test
inner join clients_MRS
on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
where SCID = '$ID';";
$rs2 = mysqli_query($con,$getmr);
$rvd = mysqli_fetch_assoc($rs2);
$MR = date('m/d/Y', strtotime($rvd['Manager_Review_Date']));
echo "MR: $MR<br>";
$PR = date('m/d/Y', strtotime($rvd['President_Review_Date']));
}
// The following query select the data for the row and orders it by the latest Manager Review Date.
$cliselect = "select distinct clientdb.Plans.Client_ID, clientdb.clients_MRS.DSA_Status, clientdb.clients_MRS.DSA_Status_Date, clientdb.clients_MRS.First_Name, clients_MRS.Last_Name, clientdb.clients_MRS.County, clientdb.Plans.DDD_Case, RID, Plans.Program, max(Plans.Plan) as MPlan, Tier, Plan_End_Date, clientdb.MRS2_test.RID, clientdb.MRS2_test.President_Comments, clientdb.MRS2_test.Manager_Comments, clientdb.MRS2_test.Services_Issues, clientdb.MRS2_test.Dues_List
from clientdb.Plans
inner join clientdb.clients_MRS on clientdb.clients_MRS.DDD_Case = clientdb.Plans.DDD_Case
inner join clientdb.MRS2_test on clientdb.MRS2_test.DDD_Number = clientdb.Plans.DDD_Case
where SCID = '$ID' and (DSA_Status = 'Active' OR (DSA_Status <> 'Active' AND STR_TO_DATE(DSA_Status_Date, '%d/%m/%Y') > STR_TO_DATE($firstday, '%m/%d/%Y'))) AND (Manager_Review_Date = '$MR')
group by clientdb.Plans.DDD_Case order by STR_TO_DATE(clientdb.MRS2_test.Manager_Review_Date, '%m/%d/%Y') DESC, clientdb.Plans.Last_Name;";
//echo "cliselect $cliselect<br>";
$cres = mysqli_query($con, $cliselect);
while ($dddr = mysqli_fetch_assoc($cres)) {
$DDD_Case = $dddr['DDD_Case'];
$First_Name = $dddr['First_Name'];
$Last_Name = $dddr['Last_Name'];
$County = $dddr['County'];
$Tier = $dddr['Tier'];
if($ddr['Plan_End_Date'] <> '')
{
$Plan_End_Date = $dddr['Plan_End_Date'];
}
$Pres_Comments = $dddr['President_Comments'];
$Mgr_Comments = $dddr['Manager_Comments'];
$Dues = $dddr['Dues_List'];
$Services = $dddr['Services_Issues'];
$RID = $dddr['RID'];
$mxselect = "select max(Plan) as MPlan from clientdb.Plans where clientdb.Plans.DDD_Case = '$DDD_Case';";
$rens = mysqli_query($con, $mxselect);
$rmm = mysqli_fetch_assoc($rens);
$MPlan = $rmm['MPlan'];
$endsel = "select Plan_End_Date, Program from clientdb.Plans where clientdb.Plans.DDD_Case = $DDD_Case and clientdb.Plans.Plan = $MPlan;";
$rsel = mysqli_query($con, $endsel);
$end = mysqli_fetch_assoc($rsel);
$Plan_End_Date = $end['Plan_End_Date'];
$Program = $end['Program'];
//The purpose of ths quer s to get the RID for each row.
$mrselect = "select * from MRS2_test where DDD_Number = '$DDD_Case' and Manager_Review_Date = '$MR'
group by DDD_Number, RID
order by RID DESC
Limit 1 ;";
$run = mysqli_query($con,$mrselect);
$mrss = mysqli_fetch_assoc($run);
$Manager_Review_Date = $mrss['Manager_Review_Date'];
$President_Review_Date = $mrss['President_Review_Date'];
$myRID = $mrss['RID'][$n];
echo "<tr><td>$o</td><td sorttable_customkey='$DDD_Case'><input class='ddd' type = 'text' value = '$DDD_Case' name = 'DDD_Number[]' size='6'></td><td sorttable_customkey='$Last_Name'>$First_Name $Last_Name</td><td>$County</td><td>$Program</td><td>$Tier</td><td sorttable_customkey='";
?>
<?php echo strtotime($Plan_End_Date);
echo "'>$Plan_End_Date</td><td><textarea class='expnd' name='Services[]'>$Services</textarea></td><td><input name='Dues_List[]'' type = 'text' value = '$Dues'></td><td><textarea class='expnd' name='Manager_Comments[]'>$Mgr_Comments</textarea></td><td><textarea class='expnd' name='President_Comments[]'>$Pres_Comments</textarea></td><td><input type='text' size='4' name = 'myrid[]' value='$RID' readonly></td><input type='hidden' name = 'manreview-orig' value='$Manager_Review_Date'></tr>";
$n = $n++;
$o++;
}
?>
And finally, this is the code that does the update:
<?php
include 'config.php';
$con = mysqli_connect($DB_server, $DB_user, $DB_password, $DB_database);
$Manager_Review = $_GET['Manager_Review'];
$Old_MR = $_GET['manreview-orig'];
//echo "OLD MR: $Old_MR<br>";
if($_GET['President_Review'] == '12/31/1969')
{
$President_Review = '';
}
if($_GET['President_Review'] <> '')
{
$President_Review = $_GET['President_Review'];
}
else
{
$President_Review = '';
}
$ID = $_GET['ID'];
$Services = $_GET['Services'];
echo "New Content!<br>";
$n = 0;
while ($n <= sizeof($_GET)) {
$ridselect = "select clientdb.MRS2_test.RID, clientdb.clients_MRS.DDD_Case, clientdb.clients_MRS.SCID from clientdb.MRS2_test
inner join clientdb.clients_MRS
on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
where Manager_Review_Date = '$Old_MR' and clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
order by RID;";
$rsc = mysqli_query($con, $ridselect);
$rowrid = mysqli_fetch_assoc($rsc);
$RID = $_GET['myrid'][$n];
// echo "RID: $RID<br>";
$MDD = $_GET['RID'];
$myrid = $_GET['myrid'][$n];
$DDD_Case = $_GET['DDD_Number'][$n];
$Period = ltrim(substr($Manager_Review,0,2), "0");
$Services = mysqli_real_escape_string($con, $_GET['Services'][$n]);
$Manager_Comments = mysqli_real_escape_string($con, $_GET['Manager_Comments'][$n]);
$President_Comments = mysqli_real_escape_string($con, $_GET['President_Comments'][$n]);
$Dues_List = mysqli_real_escape_string($con, $_GET['Dues_List'][$n]);
$DDD_Case = $_GET['DDD_Number'][$n];
$updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Services_Issues = '$Services',
clientdb.MRS2_test.Manager_Comments = '$Manager_Comments', clientdb.MRS2_test.President_Comments = '$President_Comments',
clientdb.MRS2_test.Dues_List = '$Dues_List', Period = '$Period' where DDD_Number = '$DDD_Case' and RID = '$RID';";
echo $updater . "<br>";
$date_updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Manager_Review_Date = '$Manager_Review',
clientdb.MRS2_test.President_Review_Date = '$President_Review' where RID = '$RID';";
echo "dateupdater: $date_updater<br>";
if(!mysqli_query($con, $date_updater))
{
echo "That failed miserably.<br>";
}
else
{
$rws = mysqli_affected_rows($con);
echo "affected rows: $rws<br>";
echo "Success.<br>";
}
mysqli_query($con, $updater);
$datestamp = date('Y-m-d h:i:s');
$upstamp = "update clientdb.MRS2_test set Update_Time = '$datestamp' where DDD_Case = '$DDD_Case' and RID = '$RID';";
mysqli_query($con,$upstamp);
$n++;
}
echo "<script language='Javascript'>document.getElementById('stuffhere').InnerHTML = '<?php echo $updater; ?>';</script>";
?>
I've tried serializing the form, and I haven't had any success there. Any suggestions would be greatly welcome. Sorry for the long post, but I'm just not sure where the error is at this point.
Your code
var data= [DDD_Number,Manager_Review,RID,Services,Dues_List,ID,myrid,Manager_Comments,President_Comments];
var datatosend = JSON.stringify(data);
$.ajax({
type: "GET",
url:'baseupdater-test.php',
data:dataTosend,
async: true,
success:function(data){
document.getElementById('stuffhere').innerHTML.text = "Success.";
document.getElementById('stuffhere').innerHTML.text = data;
},
error: function(data){
document.getElementById('stuffhere').innerHTML.text = "Failure.";
}
});
As i can see you are trying to send the data twice, first through url and second with the ajax data method please fix that i think its a wrong approach to do that you should send it only once.
And moreover you must convert the data into json format to make the ajax request work
and now what's happening is as your data is not in the correct format your code must be stuck at the data in ajax you can see it in console the ajax request would not show you any value passing to another and that is the main reason the Success or Failure are not being show.

refresh multiple classes every n secs from php backend

I have some code in jquery that connects to php and refreshes the class with latest data. This is working ok. However, I need to update 3 classes and when it refreshses the values are empty.
Is there a way I can query db and update 3 classes with fresh data every n sec. Many thanks
js
// Update server with latest actions,destructions and return requests
setInterval(function() {
$.get('/domain/admin/refreshBox.php', function(data) {
$(".actions").text(data);
$(".retrievals").text(data);
$(".returns").text(data);
});
}, 10000);
php
$sql= mysqli_query($conn,"SELECT count(*) as total FROM act WHERE new = '1'");
$rows = mysqli_fetch_assoc($sql);
$num = $rows['total'];
//echo $num;
$ni = $num;
if($ni < 1) {
$ni = '0';
}
echo $ni;
$nisql= mysqli_query($conn,"SELECT count(*) as ni FROM act WHERE activity='New Intake' AND new = '1'");
$niintknum_row = mysqli_fetch_assoc($nisql);
$niintknum = $niintknum_row['ni'];
//echo $num;
$niintk_num = $niintknum;
if($niintk_num < 1) {
$niintk_num = '0';
echo $niintk_num;
$brtvsql= mysqli_query($conn,"SELECT count(*) as rtrv FROM act WHERE activity='Box Retrieval' AND new = '1'");
$brtv_row = mysqli_fetch_assoc($brtvsql);
$brtvnum = $brtv_row['rtrv'];
//echo $num;
$brtv_num = $brtvnum;
if($brtv_num < 1) {
$brtv_num = '0';
echo $brtv_num;
$brtnsql= mysqli_query($conn,"SELECT count(*) as brtn FROM act WHERE activity='Box Return' AND new = '1'");
$brtn_row = mysqli_fetch_assoc($brtnsql);
$brtnnum = $brtn_row['brtn'];
//echo $num;
$brtn_num = $brtnnum;
if($brtn_num < 1) {
$brtn_num = '0';
}
echo $brtn_num;

check duplicate rand function value in database and generate it again

i create rand funtion for generating random value and concatenate with other value and show in the text field through ajax before insert this value. but here how can i check this random generating value is exists or not in database before inserting this value in database.if value is exists then again generate rand function value and again concatenate this and show the value in textbox. how can i do this? my code is below
index.php
<html>
<head>
<title>Untitled Document</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$( document ).ready(function() {});
function my_validate_func() {
var name = $('#name').val();
var year = $('#year').val();
var course = $('#course').val();
var branch_name = $('#branch_name').val();
if ($('#name').val() != "" && $('#year').val() != "" &&
$('#course').val() != "" && $('#branch_name').val() != "") {
$.ajax({
type: "POST",
url: 'roll.php',
data: { name: name, year: year, branch_name: branch_name, course: course },
success: function(response) {
$('#roll').val(response);
}
});
}
}
</script>
</head>
<body>
<form method="post" action="">
<input type="text" name="name" id="name" onChange="my_validate_func()">
<input type="text" name="phone" id="phone" onChange="my_validate_func()">
<input type="text" name="course" id="course" onChange="my_validate_func()">
<input type="text" name="center" id="center" onChange="my_validate_func()">
<input type="text" name="roll" id="roll" value="">
</form>
</body>
</html>
roll.php
<?php
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
$roll =$branch_name.$name.$course.$year.$rand;
//return $roll;
echo $roll;
}
function isValidRoll($roll) {
mysql_connect("localhost","root","");
mysql_select_db("sigma");
$sql="SELECT count(*) as total FROM student WHERE roll = '$roll'";
$result = mysql_query($sql);
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
?>
I suggest to use md5 function and/or time() function such as:
$rand = md5(time() + rand(100000,999999));
Your updated code should be:
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = md5(time() + rand(100000,999999));
$roll = $branch_name.$name.$course.$year.$rand;
echo $roll;
This solution provide unique value. You can use also uniqid() function. Also remember to set as unique the database field.
Another solution is to keep roll creation login in a function and create another function to check if the roll exists or not. Your responsibility to check if other rolls are store in the db or in a text file, ...
function calculateRoll()
{
$name1 = $_POST['name'];
$year1 = $_POST['year'];
$course1 = $_POST['course'];
$branch_name1 = $_POST['branch_name'];
$name2 = substr($name1,0,3);
$name = strtoupper($name2);
$year = substr($year1,-2);
$branch_name = strtoupper(substr($branch_name1,0,3));
$course2 = substr($course1,0,3);
$course = strtoupper($course2);
$rand = rand(100000,999999);
return $branch_name.$name.$course.$year.$rand;
}
function isValidRoll($roll) {
$result = mysql_query("SELECT count(*) as total FROM student WHERE roll = '$roll'")
or die("Query not valid: " . mysql_error());
$data = mysql_fetch_assoc($result);
return $data['total'] == 0;
}
$validRoll = false;
$roll = calculateRoll();
while (!$validRoll) {
if (isValidRoll($roll)) {
$validRoll = true;
} else {
$roll = calculateRoll();
}
}
when ever you save the data of the form store rand function value too means in second time you can retrieve the rand function value and compare with current rand function generating value.

Submenu keep active when user click on it and open in a new page

I have problem when a visitor clicks on a submenu and the link opens in a new page, so I want to keep that submenu active on that page.
I have css class active and javascript for opening it, what I need is to make it with php to be active.
This is UL with class:
This is my code. Can it be done with php or with javascript.
<ul>
<?php
$qKategori = ("SELECT * FROM kategori WHERE kprind = 0");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {
while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)){
$emrikategorise = $exKat['kemri'];
$idkategori = $exKat['kid'];
$idprind = $exKat['kprind'];
?>
<li><?=$emrikategorise;?>
<ul>
<?php
$qPrind = ("SELECT * FROM kategori WHERE kprind = '".$idkategori."'");
$rPrind = mysqli_query($dbc,$qPrind);
while($prind = mysqli_fetch_array($rPrind)) {
?>
<li><?=$prind['kemri']?> </li>
<?php
}
mysqli_free_result($rPrind);
?>
</ul>
</li>
<?php }
mysqli_free_result($rKategori);
}
?>
</ul>
You can see menu on the left in The website is www.sitimobil.mk
You probably will need to build the array before outputting to be able to determine which menus should be active. You can also combine it with an optimization of the query to not have to do 1 query per category.
Something like:
$active = isset($_GET['kid'] ? $_GET['kid'] : -1;
$tree = array();
$list = array();
$qKategori = ("SELECT * FROM kategori ORDER BY kprind");
$rKategori = mysqli_query($dbc, $qKategori);
if ($rKategori) {
while ($exKat = mysqli_fetch_array($rKategori, MYSQLI_ASSOC)){
$id = $exKat['kid'];
//To prevent numerical array with unused space
$name = 'kategori'.$exKat['kid'];
$list[$name] = $exKat;
//Calculate depth to see if the menu is a sub..sub..sub menu etc.
$parent = $list[$name]['kprind'];
if($parent == 0) {
$list[$name]['depth'] = 0;
$list[$name]['childCount'] = 0;
}
else {
$list['kategori'.$parent]['childCount']++;
$list[$name]['depth'] = $list['kategori'.$parent]['depth']+1; //Increment
}
if($id == $active) {
$list[$name]['active'] = true;
while($parent != 0) {
$parentName = 'kategori'.$parent;
$list[$parentName]['active'] = true;
$parent = $list[$parentName]['kprind'];
}
}
else
$list[$name]['active'] = false;
}
mysqli_free_result($rPrind);
//Once we have that we can output the results...
function output_menu($list, $parent = 0, $active = false)
$activeClass = $active ? ' class="active"' : '';
echo '<ul'.$activeClass.'>';
foreach($list as $row){
if($row['kprind'] != $parent) continue;
$link = $row['kprind'] == 0 ? '#' : 'kategori.php?kid='.$row['kid'];
echo '<li>'.$row['kemri'].'';
if($row['childCount'] > 0)
output_menu($list, $row['kprind'], $row['active']);
echo '</li>';
}
echo '</ul>';
}
output_menu($list);
}
This is still a bit rough but should do the trick. It can probably be optimized so that we don't have to go through the list too many times but has the benefit of not having to request too many calls to the database. That should result in a lighter workload for the DB and faster output.

Categories

Resources