How to use loop for following Laravel code? - mysql

$query1 = User::where('sponser_id',$_SESSION['ruserid'])->get('userid');
$count1= count($query1);
$query2 = User::whereIn('sponser_id',$query1)->get('userid');
$count2= count($query2);
$query3 = User::whereIn('sponser_id',$query2)->get('userid');
$count3= count($query3);
$query4 = User::whereIn('sponser_id',$query3)->get('userid');
$count4= count($query4);
$query5 = User::whereIn('sponser_id',$query4)->get('userid');
$count5= count($query5);
$query6 = User::whereIn('sponser_id',$query5)->get('userid');
$count6= count($query6);
$query7 = User::whereIn('sponser_id',$query6)->get('userid');
$count7= count($query7);
$allcount=$count1+$count2+$count3+$count4+$count5+$count6+$count7;
I want to calculate the total downlines of users. This code works fine. But How to simplifies this code using a loop?

$allcount = 0;
$query1 = User::where('sponser_id',$_SESSION['ruserid'])->get('userid');
$count1 = count($query1);
$allcount = $allcount + $count1;
for ($i=2; $i<8; $i++) {
if ($i>2){
$j = $i-1;
${"query".$j} = User::whereIn('sponser_id',${"query".($j-1)})->get('userid');
}
${"query".$i} = User::whereIn('sponser_id',${"query".($i-1)})->get('userid');
${"count".$i} = count(${"query".$i});
$allcount = $allcount + ${"count".$i};
}
return $allcount;

Related

Subtracting fields from two different tables and updating the value during update in Laravel

I have two different tables, table_employee and table_leave. table_employee contains fields such as emp_id, paid_vacation(In Hours), used_vacation(in Hours), while table_leave contains id, hours_spent(in Hours). please how can i deduct the hours_spent in the table_leave from used from the paid_vacation in the table_employee and then update the used_vacation in table_employee with the new value
for instance. paid_vacation =150 hours, used_vacation = 0, hours_spent= 8 hours, with this, this used_vacation should be updated to 150 -8 hours = 142 hours left. I want deduct and update back in the table.
private function saveEmployeeLeave(Request $request, $id=null){
if($id != NULL){
$employeeId = DB::table('as_tbl_employee_master')
->where('employee_id', $request->employee_id)
->get();
}
$employee_id = $request->employee_id;
$paid_vacation = $request->paid_vacation;
$used_vacation = $request->used_vacation;
$empData = new AsEmployee();
if($id !== null) {
$empData = AsEmployee::find($id);
if($empData == null) {
$errors = array('Id: ' . $id . ' not exist');
return json_encode([], 400, 'Failed', $errors);
}
}
$empData->employee_id = $employee_id;
$empData->paid_vacation = $paid_vacation;
$empData->used_vacation = $used_vacation;
$empData->save();
// $emp_id = $request->emp_id;
$emp_id = $request->emp_id;
$dept = $request->department_id;
$english_name = $request->english_name;
$department = $request->department;
$selectedLeaveType = $request->selectedLeaveType;
$application_time = date('Y-m-d H:i:s');
$date_from = $request->date_from;
$date_to = $request->date_to;
$comment = $request->comment;
$contact = $request->contact;
$hours = $request->hours;
$approval_emp_id = $request->reports_to;
$manager = $request->manager;
$status = $request->status;
$empInfo = new AsEmployeeLeave();
if($id !== null) {
$empInfo = AsEmployeeLeave::find($id);
if($empInfo == null) {
$errors = array('Id: ' . $id . ' not exist');
return json_encode([], 400, 'Failed', $errors);
}
}
$empInfo->emp_id = $emp_id;
$empInfo->department_id = $dept;
$empInfo->application_time = $application_time;
$empInfo->type = $selectedLeaveType;
$empInfo->date_from = $date_from;
$empInfo->date_to = $date_to;
$empInfo->comment = $comment;
$empInfo->requester_emp_id = $emp_id;
$empInfo->requester_sign = $english_name;
$empInfo->approval_emp_id = $approval_emp_id;
$empInfo->approval_sign = $manager;
$empInfo->contact = $contact;
$empInfo->hours = $hours;
$empInfo->status = $status;
$empInfo->save();
return $empData;
}
I called it inside this function
public function addEmpLeave(Request $request){
$responseData = $this->saveEmployeeLeave($request);
return ($responseData instanceof JsonResponse) ? $responseData : $this->sendResponse($responseData);
}
Try this :
private function saveEmployeeLeave(Request $request, $id=null){
if($id != NULL){
$employeeId = DB::table('as_tbl_employee_master')
->where('employee_id', $request->employee_id)
->get();
}
$employee_id = $request->employee_id;
$paid_vacation = $request->paid_vacation;
$used_vacation = $request->used_vacation;
$empData = new AsEmployee();
if($id !== null) {
$empData = AsEmployee::find($id);
if($empData == null) {
$errors = array('Id: ' . $id . ' not exist');
return json_encode([], 400, 'Failed', $errors);
}
}
$empData->employee_id = $employee_id;
$empData->paid_vacation = $paid_vacation;
$empData->used_vacation = $used_vacation;
$empData->save();
// $emp_id = $request->emp_id;
$emp_id = $request->emp_id;
$dept = $request->department_id;
$english_name = $request->english_name;
$department = $request->department;
$selectedLeaveType = $request->selectedLeaveType;
$application_time = date('Y-m-d H:i:s');
$date_from = $request->date_from;
$date_to = $request->date_to;
$comment = $request->comment;
$contact = $request->contact;
$hours = $request->hours;
$approval_emp_id = $request->reports_to;
$manager = $request->manager;
$status = $request->status;
$empInfo = new AsEmployeeLeave();
if($id !== null) {
$empInfo = AsEmployeeLeave::find($id);
if($empInfo == null) {
$errors = array('Id: ' . $id . ' not exist');
return json_encode([], 400, 'Failed', $errors);
}
}
$empInfo->emp_id = $emp_id;
$empInfo->department_id = $dept;
$empInfo->application_time = $application_time;
$empInfo->type = $selectedLeaveType;
$empInfo->date_from = $date_from;
$empInfo->date_to = $date_to;
$empInfo->comment = $comment;
$empInfo->requester_emp_id = $emp_id;
$empInfo->requester_sign = $english_name;
$empInfo->approval_emp_id = $approval_emp_id;
$empInfo->approval_sign = $manager;
$empInfo->contact = $contact;
$empInfo->hours = $hours;
$empInfo->status = $status;
$empInfo->save();
$empData = AsEmployee::find($empData->id);
$empData->used_vacation = (int)$paid_vacation - (int)$hours;
$empData->save();
return $empData;
}

Cakephp 3 how do i save individual date in database

I have leave request form.If users takes 2/3 days leaves, then the leave date should be stored into the database separately.I have applied for 2 days, suppose i have selected the date 20-10-2019 and 21-10-2019 for leave request. But it stored into database only one entry. date_form and date_to are my column names.
I want to separate the dates. Example : date_from: 20-10-2019 date_to : 20-10-2019 and date_from: 21-10-2019 date_to : 21-10-2019.
But now it stored date_from : 20-10-2019 date_to : 21-10-2019. Can anyone help me on this?
I have tried some code:
else if($leaveRequest->no_of_days > 1 && $leaveRequest->no_of_days < 7)
{
for($i = 0 ; $i < $leaveRequest->no_of_days; $i++)
{
$day = $i. ' day';
$var = $this->EmpLeaves->newEntity();
if($i == 0)
{
$var->date_from = date('Y-m-d', strtotime($this->request->getData(['date_from'])));
$var->date_to = date('Y-m-d', strtotime($this->request->getData(['date_from'])));
}
else
{
$var->date_from = date('Y-m-d', strtotime($day,strtotime($this->request->getData(['date_from']))));
$var->date_to = date('Y-m-d', strtotime($day,strtotime($this->request->getData(['date_from']))));
}
$var->employee_id = $this->Auth->user('id');
$var->employee_name = $this->request->getData(['employee_name']);
$var->reporting_managerId = $this->request->getData(['reporting_managerId']);
$var->leave_type = $this->request->getData(['leave_type']);
// $var->no_of_days = $this->request->getData(['no_of_days']);
$var->no_of_days = 1;
$var->half_day = $this->request->getData(['half_day']);
$var->leave_reason = $this->request->getData(['leave_reason']);
$var->reliever = $this->request->getData(['reliever']);
$valueSaved = $this->EmpLeaves->save($var);
}
if($valueSaved)
{
//newcode for sending email
$applierEmail = $this->Auth->user('office_email');
$applierName = $this->Auth->user('first_name') . ' ' . $this->Auth->user('last_name');
}
else
{
$this->Flash->error(__('Please check the message'));
}
}
else if($leaveRequest->no_of_days > 1 && $leaveRequest->no_of_days < 7)
{
for($i = 0 ; $i < $leaveRequest->no_of_days; $i++)
{
$day = $i. ' day';
$var = $this->EmpLeaves->newEntity();
else
$var->date_from = date('Y-m-d', strtotime($day,strtotime($this->request->getData(['date_from']))));
$var->date_to = date('Y-m-d', strtotime($day,strtotime($this->request->getData(['date_to']))));
$var->employee_id = $this->Auth->user('id');
$var->employee_name = $this->request->getData(['employee_name']);
$var->reporting_managerId = $this->request->getData(['reporting_managerId']);
$var->leave_type = $this->request->getData(['leave_type']);
$var->no_of_days = $this->request->getData(['no_of_days']);
$var->half_day = $this->request->getData(['half_day']);
$var->leave_reason = $this->request->getData(['leave_reason']);
$var->reliever = $this->request->getData(['reliever']);
$valueSaved = $this->EmpLeaves->save($var);
}
if($valueSaved)
{
//newcode for sending email
$applierEmail = $this->Auth->user('office_email');
$applierName = $this->Auth->user('first_name') . ' ' . $this->Auth->user('last_name');
}
else
{
$this->Flash->error(__('Please check the message'));
}
}

How to use SQL and PHP multiple criteria?

If my original code like this
if (!isset($_GET['page'])) {
$page = 1;
} else {
$page = $_GET['page'];
}
if (!isset($_GET['urut'])) {
$urut = "" ;
} else {
$urut = $_GET['urut'];
}
if($urut == 0){ $urutkan = "id DESC"; };
if($urut == 1){ $urutkan = "harga ASC"; };
if($urut == 2){ $urutkan = "harga DESC"; };
if (!isset($_GET['jenis'])) {
$jenis = [] ;
} else {
$jenis = $_GET['jenis'];
}
if (!isset($_GET['kategori'])) {
$kategori = [] ;
} else {
$kategori = $_GET['kategori'];
}
if (!isset($_GET['wilayah'])) {
$wilayah = [];
} else {
$wilayah = $_GET['wilayah'];
}
$results_per_page = 10;
$sql = "SELECT * FROM item ";
$result = mysqli_query($link, $sql);
$number_of_results = mysqli_num_rows($result);
$number_of_pages = ceil($number_of_results/$results_per_page);
$first_page = ($number_of_results/$number_of_results);
$last_page = $number_of_pages;
$this_page_first_result = ($page-1)*$results_per_page;
$previous = ($page-1);
$next = ($page+1);
$sql='SELECT * FROM item LIMIT ' . $this_page_first_result . ',' . $results_per_page ;
$result = mysqli_query($link, $sql);
What is the right syntax if i want the output like this
$sql='SELECT * FROM item WHERE jenis LIKE '$jenis' AND kategori LIKE '$kategori' AND wilayah LIKE '$wilayah' ORDER BY '$urutkan' LIMIT ' . $this_page_first_result . ',' . $results_per_page ;
Thx for help
...............................................................................................................................................................................................................................................................................................................................
For use multiple criteria into MySQL query you have to use AND operator in query.
Below i give an sample to use criteria with LIKE clause.
SELECT * FROM item WHERE jenis LIKE '%'.$jenis.'%' AND kategori LIKE '%'.$kategori.'%' AND wilayah LIKE '%'.$wilayah.'%' ORDER BY $urutkan
LIMIT $this_page_first_result . ',' . $results_per_page

MySQL Limit 2 How to select second row

$sMonOperationHours = "SELECT * FROM ".COMPANY_OPERATION_HOURS_TBL." WHERE
f_company_id = '$g_companyid' AND f_day = 'MON' LIMIT 2";
$rsMonOperationHours = mysql_query($sMonOperationHours);
$rowMonOperationHours = mysql_fetch_array($rsMonOperationHours);
$iMonStartTime = $rowMonOperationHours['f_start_time'];
$iMonStartTime2 = ???;
$iMonEndTime = $rowMonOperationHours['f_end_time'];
$iMonEndTime2 = ???;
After limiting my SQL query result to 2, how do I select the f_start_time and f_end_time for the second row?
You can use in LIMIT and OFFSET for getting the second result
$sMonOperationHours = "SELECT * FROM ".COMPANY_OPERATION_HOURS_TBL." WHERE
f_company_id = '$g_companyid' AND f_day = 'MON' LIMIT 1 OFFSET 1";
$rsMonOperationHours = mysql_query($sMonOperationHours);
$rowMonOperationHours = mysql_fetch_array($rsMonOperationHours);
$iMonStartTime = $rowMonOperationHours['f_start_time'];
$iMonEndTime = $rowMonOperationHours['f_end_time'];
Another way to do this, is if you want both of results, that is the way:
$sMonOperationHours = "SELECT * FROM ".COMPANY_OPERATION_HOURS_TBL." WHERE
f_company_id = '$g_companyid' AND f_day = 'MON' LIMIT 2";
$rsMonOperationHours = mysql_query($sMonOperationHours);
$rowsData = array();
$i = 0;
while ($row = mysql_fetch_array($rsMonOperationHours)) {
$rowsData[$i] = array();
$rowsData[$i][] = $row['f_start_time'];
$rowsData[$i][] = $row['f_end_time'];
$i++;
}
All data will be saved in rowsData which contains the results in array.

How to select latest change done in the given Table structure?

I have a Table structure as
id, trackid, table_name, operation, oldvalue, newvalue, field, changedonetime
Now if I have 3 rows for the same "trackid" same "field", then how can i select the latest out of the three?
i.e. for e.g.:
id = 100 trackid = 152 table_name
= jos_menu operation= UPDATE oldvalue = IPL newvalue = IPLcccc
field = name live = 0 changedonetime =
2010-04-30 17:54:39
and
id = 101 trackid = 152 table_name =
jos_menu operation= UPDATE oldvalue
= IPLcccc newvalue = IPL2222 field = name live = 0 changedonetime =
2010-04-30 18:54:39
As u can see above the secind entry is the latest change,
Now what query I shoud use to get the only one and Latest row out of many such rows...
UPDATED
$distupdqry = "select DISTINCT trackid,table_name from jos_audittrail where live = 0 AND operation = 'UPDATE'";
$disupdsel = mysql_query($distupdqry);
$t_ids = array();
$t_table = array();
while($row3 = mysql_fetch_array($disupdsel))
{
$t_ids[] = $row3['trackid'];
$t_table[] = $row3['table_name'];
//$t_table[] = $row3['table_name'];
}
//echo "<pre>";print_r($t_table);echo "<pre>";
//exit;
for($n=0;$n<count($t_ids);$n++)
{
$qupd = "SELECT * FROM jos_audittrail WHERE operation = 'UPDATE' AND trackid=$t_ids[$n] order by changedone DESC ";
$seletupdaudit = mysql_query($qupd);
$row4 = array();
$audit3 = array();
while($row4 = mysql_fetch_array($seletupdaudit))
{
$audit3[] = $row4;
}
$updatefield = '';
for($j=0;$j<count($audit3);$j++)
{
if($j == 0)
{
if($audit3[$j]['operation'] == "UPDATE")
{
//$insqry .= $audit2[$i]['operation']." ";
//echo "<br>";
$updatefield .= "UPDATE `".$audit3[$j]['table_name']."` SET ";
}
}
if($audit3[$j]['operation'] == "UPDATE")
{
$updatefield .= $audit3[$j]['field']." = '".$audit3[$j]['newvalue']."', ";
}
}
/*echo "<pre>";
print_r($audit3);
exit;*/
$primarykey = "SHOW INDEXES FROM `".$t_table[$n]."` WHERE Key_name = 'PRIMARY'";
$prime = mysql_query($primarykey);
$pkey = mysql_fetch_array($prime);
$updatefield .= "]";
echo $updatefield = str_replace(", ]"," WHERE ".$pkey['Column_name']." = '".$t_ids[$n]."'",$updatefield);
}
Here I am creating the Update query by fetching the records from the initially described table which is here mentioned as audittrail table... please go throught the code.. and see how can i make the required change i need finally..
select * from TableName order by id DESC LIMIT 1
EDITED. YEs you can if you want to order by "changedonetime" USE.
select * from TableName order by changedonetime DESC LIMIT 1