Fetching latest value from database even when there are no rows present - php

So I'm trying to fetch a points table for users to add points in by garnering their total points and adding it with the installation points, however by trying to fetch their "latest" points, new users who do not have an existing row in the table will throwback an error "InvalidArgumentException; Data Missing". This would be my code below, and are there any other ways around this?
$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first();
$points['user_id'] = $input['user_id'];
$points['points_add'] = $battery['point_installation'];
$points['points_subtract'] = 0;
$points['points_total'] = $currentpoint + $battery['point_installation'];
$points['points_source_id'] = 1;
$points['created_at'] = $mytime;
$points['updated_at'] = $mytime;
$point = Points::create($points);

$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first(); of your code return an object and you are try to perform math (addition) operation on that object which is not possible. You can update your code like below.
$currentpoint = Points::where('user_id', $input['user_id'])->latest()->first();
$points['user_id'] = $input['user_id'];
$points['points_add'] = $battery['point_installation'];
$points['points_subtract'] = 0;
if($currentpoint != null)
{
$points['points_total'] = $currentpoint->points_total + $battery['point_installation'];
}
else {
$points['points_total'] = $battery['point_installation'];
}
$points['points_source_id'] = 1;
$points['created_at'] = $mytime;
$points['updated_at'] = $mytime;
$point = Points::create($points);

Related

Multiple if statements with GET not outputting correctly in PHP with XPath

I'm trying to get the total times two authors have edited or coauthored books. (They are selected by a user using checkboxes, so I've used GET to see if the checkbox is selected).
I am cross referencing the authors 'a' (mj) and 'b' (ms) from 'a's' (mj) xml doc that features all their publishing information.
Currently I have this:
if ($_GET['author'] == 'mj55'){
$getMj = new DOMDocument();
$getMj->load("Margret-Jane.xml");
$mjxpath = new DOMXpath($getMj);
$mjAuth = $mjxpath->query("////author[#id = 'mj55']")->length;
$mjEdit = $mjxpath->query("////editor[#id = 'mj55']")->length;
$mjResult = ($mjAuth + $mjEdit);
if ($_GET['author'] == 'ms10' ) {
$mjmsA = $mjxpath->query("////author[#id = 'ms10']")->length;
$mjmsE = $mjxpath->query("////editor[#id = 'ms10']")->length;
$mjmsTotal = ($mjmsA + $mjmsE);
echo $mjmsTotal;
}
}
if I put an echo $mjResult at the end of the first if statement, I get the correct output. But I don't get any output at all from the echo $mjmsTotal
you used a nested if and that's why you are getting a result of only first if.. try to use both the if statement totally independent with each other. Here is an example-
$getMj = new DOMDocument();
$getMj->load("Margret-Jane.xml");
$mjxpath = new DOMXpath($getMj);
if ($_GET['author'] == 'mj55'){
$mjAuth = $mjxpath->query("////author[#id = 'mj55']")->length;
$mjEdit = $mjxpath->query("////editor[#id = 'mj55']")->length;
$mjResult = ($mjAuth + $mjEdit);
}
if ($_GET['author'] == 'ms10' ) {
$mjmsA = $mjxpath->query("////author[#id = 'ms10']")->length;
$mjmsE = $mjxpath->query("////editor[#id = 'ms10']")->length;
$mjmsTotal = ($mjmsA + $mjmsE);
echo $mjmsTotal;
}
You can reduce this to one condition, this saves having to hard code all of the different authors/editors.
First check if the author is set, then include this value in the XPath expressions...
if ( !empty($_GET['author'])) {
$getMj = new DOMDocument();
$getMj->load("Margret-Jane.xml");
$mjxpath = new DOMXpath($getMj);
$mjAuth = $mjxpath->query("//author[#id = '{$_GET['author']}']")->length;
$mjEdit = $mjxpath->query("//editor[#id = '{$_GET['author']}']")->length;
$mjResult = ($mjAuth + $mjEdit);
echo $mjResult;
}

Same serial number is generating for different requests

I am inserting a serial number in a table that is increment by one always but when multiple request is coming in same time it is inserting same serial number for different requests.I am using mysql database.
I know i am fetching the max serial number too early in the code and if request is come in same time so it will fetching same serial number for both. is it good idea to update serial number after all work done. what if inserting a record for new request and updating the serial number for previous one is in same time.
public function add(){
$session = $this->request->session();
$company_id = $session->read('Admin.company_id');
$emp_id = $session->read('Admin.emp_id');
$user_email_id = $session->read('Admin.email_id');
$employee_name = $session->read('Admin.employee_name');
$conn = ConnectionManager::get('default');
if ($this->request->is('post')) {
try{
$conn->begin();
$department = $this->request->data['department'];
$data = $this->request->data;
if(!array_key_exists('is_requisition_for_contractor', $data)){
$is_requisition_for_contractor = 0;
} else {
$is_requisition_for_contractor = $data['is_requisition_for_contractor'];
}
if(!array_key_exists('is_requisition_for_employee', $data)){
$is_requisition_for_employee = 0;
} else {
$is_requisition_for_employee = $data['is_requisition_for_employee'];
}
if(!array_key_exists('is_boulder_requisition', $data)){
$is_requisition_for_boulder = 0;
} else {
if($data['is_boulder_requisition'] == ''){
$is_requisition_for_boulder = 0;
} else {
$is_requisition_for_boulder = $data['is_boulder_requisition'];
}
}
$is_requisition_for_plant = 0;
if(!array_key_exists('is_plant_requisition', $data)){
$is_requisition_for_plant = 0;
} else {
if($data['is_plant_requisition'] == ''){
$is_requisition_for_plant = 0;
} else {
$is_requisition_for_plant = $data['is_plant_requisition'];
}
}
if(array_key_exists("files",$this->request->data)) {
$files = $this->request->data['files'];
if (count($files)) {
$files_uploading_response = $this->uploadMultipleFiles($files, 'files/requisitions/');
}
}
$last_material_insert_id = '';
if($this->request->data('material_id')[0] == ''){
if($this->request->data('department') == 1){
$type = 1;
} elseif($this->request->data('department') == 3){
$type = 3;
} elseif($this->request->data('department') == 2){
$type = 2;
}
if($this->request->data('department') == 1 || $this->request->data('department') == 3){
$conn->execute("INSERT INTO material (material_name, material_type_id, company_id, status, is_approved_by_admin) VALUES (?,?,?,?,?)",[$this->request->data('material_name'), $type, $company_id, 1,0]);
$last_material_insert_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
} elseif($this->request->data('department') == 2) {
//todo for unapproved material
$conn->execute("INSERT INTO material (part_no, material_type_id, company_id, status, is_approved_by_admin,unique_category_id) VALUES (?,?,?,?,?,?)",[$this->request->data('part_no')[0], $type, $company_id, 1,0,$this->request->data('unique_category_id')[0]]);
$last_material_insert_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
}
}
// here i am fatching max serial number from table
$requistion_number = $conn->execute("SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no FROM requisition WHERE site_id = ?",[$this->request->data('site_id')])->fetchAll('assoc');
$Requisition = TableRegistry::get('requisition');
$requisition = $Requisition->newEntity();
$requisition->registered_on = $this->request->data['date'];
$requisition->department_id = $this->request->data('department');
$requisition->site_id = $this->request->data('site_id');
$requisition->issues_to_id = $this->request->data['prepared_by_id'];
$requisition->prepared_by_id = $this->request->data['prepared_by_id'];
$requisition->approved_by_id = $this->request->data['hod_id'];
$requisition->hod_id = $this->request->data['hod_id'];
$requisition->is_diesel_requisition_for_employee = $is_requisition_for_employee;
$requisition->is_diesel_requisition_for_contractor = $is_requisition_for_contractor;
$requisition->is_requisition_for_boulder = $is_requisition_for_boulder;
$requisition->is_requisition_for_plant = $is_requisition_for_plant;
if(array_key_exists('for_tanker_stock', $this->request->data)) {
$requisition->for_tanker_stock = 1;
}
if($last_material_insert_id != ''){
$requisition->is_material_approved_by_admin = 0;
}
$requisition->status = 1;
$site_id = $this->request->data['site_id'];
$requisition->requisition_no = $requistion_number[0]['requisition_no'] + 1;
$requistionnumber = $requistion_number[0]['requisition_no'] + 1;
$saveRequsition = $Requisition->save($requisition);
$conn->commit();
}
I am expecting the output different serial number for each request.any optimise way to do this. thanks in advance.
Ok, how about the same strategy, setting the $requisition_number after the row has been inserted (see my other answer), but using a single query with the same method you use to determine the new requisition id:
$conn->execute("UPDATE requisition
SET requisition_no = (SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no FROM requisition WHERE site_id = ?) + 1",
[$this->request->data('site_id')]);
The idea here is that a single query will be executed in one step, without another, similar query, being able to interfere.
What you currently do is to first get the old requistion number like this:
$requistion_number = $conn->execute("SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no
FROM requisition WHERE site_id = ?",[$this->request->data('site_id')])->fetchAll('assoc');
and then increase it before you save and commit.
My suggestion is to not set the $requistion_number at all before you save and commit the requisition row, but to determine the $requistion_number afterwards.
You now wonder how?
Well, you need to count the total number of requisition rows in the table for the site the requisition is for, and add one, like this:
$last_requisition_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
$site_id = $this->request->data('site_id');
$requisition_number = $conn->execute("SELECT COUNT(*) AS requisitionsCount
FROM requisition
WHERE <primary_key> <= ? AND
site_id = ?",
[$last_requisition_id, $site_id]) + 1;
$conn->execute("UPDATE requisition
SET requisition_no = ?
WHERE <primary_key> <= ?",
[$requisition_number, $last_requisition_id]);
I know this code is not working. The $requisition_number will probably contain an array with the requisitionsCount as a value, but you can correct that.
Because you're using data that is already present in the database table you don't run the risk that two rows will get the same $requisition_number. The assumption here is that requisitions are never deleted.

is there any possible chance when i input data into loop and doesnt entered into database?

sorry for my bad english . i got problem with looping . my friend said when he used my program and he insert 20 data or more into database in one time , sometimes a data doesnt match with data previously entered .
an example : he insert 20 data and he just got 19 but the problem is that happening sometimes.
so im confused now , how can the program error just sometimes ?
here my code :
else if ($mod == 'suratkeluar'){
$batas = $_GET['batas'];
if (isset($_POST['submit'])) {
for ($i = 0; $i < $batas; $i++) {
$idlot = $_POST['hiddenlot'][$i];
$idbenang = $_POST['hiddenbenang'][$i];
$benang = $_POST['jenisbenang'][$i];
$warna = $_POST['warna'][$i];
$lot = $_POST['lot'][$i];
$harga = $_POST['hiddenprice'][$i];
$netto = $_POST['netto'][$i];
$box = $_POST['box'][$i];
$cones = $_POST['cones'][$i];
$ket = $_POST['keterangan'][$i];
$cussplit = explode('_',$_POST['customer']);
$idcus = $cussplit[0];
$cus = $cussplit[1];
$alamatcus = $cussplit[2];
$kota = $cussplit[3];
$POsplit = explode('_',$_POST['nopo']);
$idpo=$POsplit[0];
$nopo=$POsplit[1];
$mobilsplit = explode('_',$_POST['kendaraan']);
$kendaraan = $mobilsplit[0];
$plat = $mobilsplit[1];
$identitas = $_POST['identitas'][$i];
$month = date('n');
$years=date('Y');
if($idlot != 0){
$a=mysql_query("INSERT INTO surat_jalan VALUES ('',now(),'$_POST[nosurat]','$idlot','$benang','$warna','$lot','$harga','$netto','$box','$cones','$idcus','$cus','$alamatcus','$kota','$idpo','$nopo','$ket',1,'$month$years','$identitas','$kendaraan','$plat','$idbenang')");
$aax=mysql_query("SELECT * FROM lot WHERE id_lot='$idlot'");
$xx=mysql_fetch_array($aax);
$net=$xx['netto'] - $netto;
$bbox=$xx['box'] - $box;
$ccones=$xx['cones'] - $cones;
if($net == 0)
{
$a= mysql_query("UPDATE lot SET netto = '$net',
box = '$bbox',
cones = '$ccones',
warning = 1
WHERE id_lot = '$idlot'");
}
else
{
$a=mysql_query("UPDATE lot SET netto = '$net',
box = '$bbox',
cones = '$ccones'
WHERE id_lot = '$idlot'");
}
}
$b = $i + 1;
for ($c = 0; $c < $box; $c++) {
$packinglist = $_POST["packinglist$b"][$c];
$a= mysql_query("INSERT INTO packing_list VALUES('','$packinglist','$surat[id_surat]','$surat[no_surat_jalan]')");
}
}
}
}
How about this? I'll give an example but this could go with (probably) all queries. Let's say, this one (second from the last):
$a = mysql_query("UPDATE lot SET netto = '$net', box = '$bbox', cones = '$ccones' WHERE id_lot = '$idlot'");
To check if it was successful, you can add additional lines:
if ($a) // Success?
print("Row has been updated.<br>");
else // Error
print("An error has occured; row has not been updated. Reason: ".mysql_error()."<br>");
If there are no redirections at the end, etc. and there is at least one error (the last one?), then your friend will see something like this:
An error has occured; row has not been updated. Reason: #1054 - Unknown column 'cones' in 'where clause'
An error has occured; row has not been updated. Reason: #1054 - Unknown column 'box' in 'field list'
With that help, you can see if there is an error in your queries or in application itself (timeout?).
There is also another problem: you're using PHP's mysql_API, which is deprecated. Instead, you should upgrade and use mysqli_API.

How to loop through an array and add to it in JSON

I have an array containing several variables from my sql database.
{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"}, {"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}
I have an additional variable called $score that uses information from the database to calculate this score. I want to know how I can loop through and add the correct score to each country in the array.
My Original Code:
$row = $res->fetchRow();
$resGold = $row['gold'];
$resSilver = $row['silver'];
$resBronze = $row['bronze'];
$resGdp = $row['gdp'];
$resPopulation = $row['population'];
$resCountry = $row['country_name'];
$gold_score = ($resGold * $gold_value);
$silver_score = ($resSilver * $silver_value);
$bronze_score = ($resBronze * $bronze_value);
if($population == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resPopulation);
}
else if($gdp == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resGdp);
}
$result = $res->fetchAll();
$result[] = array('score' => $score);
echo json_encode($result);
Your code will be something like this:
$json_data = '{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"},
{"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}';
$countries_info_new = array();
$countries_info = json_decode($json_data);
foreach($countries_info as $country_info){
$country_info['score'] = Get_country_score($country_info['country_name']);
$countries_info_new[]=$country_info;
}
$new_json_data = json_encode($countries_info_new);

How do I delete course enrolments in moodle in bulk?

Moodle has a built in per course reset ability. I want to reset all my courses.
Sorry to bring this old post back but after a long struggle I finally got that code to work. I've tested it on a Moodle 1.9.7 enviroment
<?php
require('../config.php');
require_once('reset_form.php');
$courseids = array(8,9,11);
foreach ($courseids as &$value) {
$data->MAX_FILE_SIZE = 8097152;
$data->reset_start_date = 1251781200;
$data->reset_events = 1;
$data->reset_logs = 1;
$data->reset_notes = 1;
$data->reset_roles = Array(5);
$data->mform_showadvanced_last = 0;
$data->reset_roles_local = 1;
$data->reset_gradebook_grades = 1;
$data->reset_assignment_submissions = 1;
$data->reset_forum_all = 1;
$data->reset_quiz_attempts = 1;
$data->id = $value;
require_login($value);
require_capability('moodle/course:update', get_context_instance(CONTEXT_COURSE, $value));
$status = reset_course_userdata($data);
}
?>
Ok, I figued it out, but be very carful. If you do not know what you are doing do not use this code, you could do a lot of damage to your DB. This does the "default" course reset to all course ids in the array.
<?php
require('../config.php');
require_once('reset_form.php');
$courseids = array(8,9,11);
foreach ($courseids as &$value) {
$data->MAX_FILE_SIZE = 8097152;
$data->reset_start_date = 1251781200;
$data->reset_events = 1;
$data->reset_logs = 1;
$data->reset_notes = 1;
$data->reset_roles = Array(5);
$data->mform_showadvanced_last = 0;
$data->reset_roles_local = 1;
$data->reset_gradebook_grades = 1;
$data->reset_assignment_submissions = 1;
$data->reset_forum_all = 1;
$data->id = $value;
$status = reset_course_userdata($data);
}
?>
You should not reset courses this way, its too risky. Use the Course administration feature Choose the course, find the course admin. block, click the reset button, very simple. If you have only 3 courses, this takes about 30 seconds.

Categories