How to increment field value count using MySQL [duplicate] - mysql

I have a table student attendance.
Fields/data sample
id | studid | cls_id | smonth | syear | total_p | total_a
1 | 20 | 2 | 08 | 2015 | 2 | 1
2 | 21 | 2 | 08 | 2015 | 1 | 0
3 | 22 | 2 | 08 | 2015 | 2 | 1
I want, to check what is the total_p and total_a value of each students in last update and then increment 1.
If I am enter the both students are present = 1 so I want total_p value 20=3, 21=2, 22=3
How to get database field values and increment 1's.?
My controller
$present = Input::get($student->id);
if ($checkatt)
{
if ($present == 1)
{
DB::table($wys_total_attend_table)->where('studid', $student->id)
->where('smonth', $date_exploded[1])
->where('syear', $date_exploded[2])
->where('stotal_p', 1)
->update(array(
'stotal_p' => 1 + 1,
));
DB::table($wys_total_attend_table)->where('studid', $student->id)
->where('smonth', $date_exploded[1])
->where('syear', $date_exploded[2])
->where('stotal_p', 0)
->update(array(
'stotal_p' => 1,
'stotal_a' => 0,
));
} elseif ($present == 0)
{
DB::table($wys_total_attend_table)->where('studid', $student->id)
->where('smonth', $date_exploded[1])
->where('syear', $date_exploded[2])
->where('stotal_a', 1)
->update(array(
'stotal_a' => 1 + 1,
));
DB::table($wys_total_attend_table)->where('studid', $student->id)
->where('smonth', $date_exploded[1])
->where('syear', $date_exploded[2])
->where('stotal_a', 0)
->update(array(
'stotal_a' => 1,
));
DB::table($wys_total_attend_table)->where('studid', $student->id)
->where('smonth', $date_exploded[1])
->where('syear', $date_exploded[2])
->where('stotal_p', 1)
->where('stotal_a', 0)
->update(array(
'stotal_a' => 0 + 1,
));
}
}

I think u just want to update each record of total_p and total_a column just make it simple:
//get the id of student
$student_id = Input::get('student_id');
$present = Input::get('status'); //dropdown value 0,1
//You need a model for your table let say:
#Student.php
<?php
class Student extends Eloquent{
protected $table = 'students'; //table name
}
//Your Controller codes
public function findStudent($id, $status){
$query=Student::find($id);
if($query->count() && $status==1 ){ //status 1 = present
$query->total_p += 1; //plus one value in the total_p column in the tbl.
$query->save();
}else{
$query->total_a +=1;
$query->save();
}
}

Related

Transpose rows to column grouped by a column in Googles Sheets

Change data in Google sheet for better understanding based on a column value
From this:
entity_id | data_key | data_value
1 | name | some name
1 | author | john
1 | likes | 12
2 | name | another name
2 | author | sam
3 | name | different name
3 | author | mary
3 | likes | 3
To this:
entity_id | name | author | likes
1 | some name | john | 12
2 | another name | sam |
3 | different name| mary | 3
I checked features like transpose, it falls short of what I actually need.
Run the function in the below snippet as a custom function:
const data = [
['entity_id', 'data_key', 'data_value'],
[1, 'name', 'some name'],
[1, 'author', 'john'],
[1, 'likes', 12],
[2, 'name', 'another name'],
[2, 'author', 'sam'],
[3, 'name', 'different name'],
[3, 'author', 'mary'],
[3, 'likes', 3],
];
/**
*#customfunction
*/
const myTranspose = range => {
range.shift();
const headers = [];
const undefToStr = value => (undefined === value ? '' : value);
const obj = range.reduce((acc, row) => {
if (!acc[row[0]]) acc[row[0]] = {};
acc[row[0]][row[1]] = row[2];
if (-1 === headers.indexOf(row[1])) headers.push(row[1]);
return acc;
}, {});
return Object.entries(obj).reduce(
(acc, entry) => {
const row = [entry[0]];
headers.forEach(header => row.push(undefToStr(entry[1][header])));
acc.push(row);
return acc;
},
[['entity_id', ...headers]]
);
};
console.log(myTranspose(data));
The result of the function in Google Sheets:
The function first builds and then transposes it into a new 2D array.
Assuming that data is located columns A to C
={A1,transpose(unique(B2:B));arrayformula(ROW(A2:A)-1),arrayformula(iferror(vlookup((row(A2:A)-1)&"|"&transpose(unique(B2:B)),{arrayformula(A2:A&"|"&B2:B),arrayformula(C2:C)},2,0)))}
https://docs.google.com/spreadsheets/d/12LOBTcialZ8wef9enII-hFsjrRnuOhx35_EXtg4Zreo/copy
Try
=newTab(A1,A2:C9)
with custom function
function newTab(title,data){
var headers=[]
var items = new Map()
var n = 0
data.forEach(function(elem){
items.set(elem[1],'')
n= Math.max(n,elem[0])
})
items.forEach(function(value, key) {headers.push(key)})
var result = Array.from({ length: n + 1 }, () => Array.from({ length: headers.length + 1 }, () => ''));
result[0] = [title, ...headers]
data.forEach(function(elem){
result[elem[0]][headers.indexOf(elem[1])+1]=elem[2]
result[elem[0]][0]=elem[0]
})
return(result)
}
https://docs.google.com/spreadsheets/d/12LOBTcialZ8wef9enII-hFsjrRnuOhx35_EXtg4Zreo/copy

Codeigniter Bootstrap add and edit record simultaneously

I have a MySQL Table, related to Codeigniter project that is used to maintain the details of files as follows (tbl_documents) :
+-----+---------+-------+------------+-----------+--------+---------+--------+
| id | file_no | name | subject_id | folder_no | row_no | rack_no | status |
+-----+---------+-------+------------+-----------+--------+---------+--------+
| 100 | GSP/01 | Test | 1 | 1 | 1 | 2 | 1 |
| 101 | GSP/02 | Test1 | 2 | 2 | 1 | 3 | 1 |
| 102 | GSP/03 | Test2 | 1 | 2 | 1 | 3 | 1 |
| 103 | GSP/04 | Test3 | 3 | 2 | 2 | 1 | 1 |
| 104 | GSP/05 | Test4 | 4 | 1 | 1 | 1 | 1 |
+-----+---------+-------+------------+-----------+--------+---------+--------+
subject_id is referenced from the following table (tbl_subjects) :
+------------+--------------+--------+
| subject_id | subject_name | status |
+------------+--------------+--------+
| 1 | A/01 | 1 |
| 2 | A/02 | 1 |
| 3 | A/03 | 1 |
| 4 | B/01 | 1 |
| 5 | B/02 | 1 |
| 6 | C/01 | 1 |
+------------+--------------+--------+
insert, update & delete records are working fine. If I edit record using an existing subject_id in the tbl_subject, the functionality is working properly. But I want to edit a record in the tbl_documents table, while inserting new subject to the tbl_subject table, the functionality is not working (My Requirement). My question is mainly aim to subject_id (s). I used the following lines in my controller.
Controller
public function store($id = null)
{
$this->form_validation->set_rules('name', "File/Document Name", 'required');
if ($this->form_validation->run()) {
$subject_id = $this->input->post('subject_id');
$sub_data = [];
$sub_data = array(
'subject_name' => $subject_id,
'status' => 1
);
$data = array(
'file_no' => $this->input->post('file_no'),
'name' => $this->input->post('file_name'),
'subject_id' => $this->input->post('subject_id'),
'folder_no' => $this->input->post('folder_no'),
'rack_no' => $this->input->post('rack_no'),
'row_no' => $this->input->post('row_no'),
'status' => 1
);
}
if ($this->form_validation->run() && $this->documents_model->save($data, $id, $sub_data)) {
if ($id)
$message = 'File/ Document Details have been Updated successfully..!!';
else
$message = 'File/ Document details have been saved successfully..!!';
$this->session->set_flashdata('message', $message);
redirect('documents');
} else {
redirect('documents');
}
}
Documents_model
public function save($item, $id, $sub_data = [])
{
$this->db->trans_start();
if (!empty($sub_data)) {
$this->db->insert('tbl_subjects', $sub_data);
$data['subject_id'] = $this->db->insert_id();
}
if ($id) {
$this->db->update('tbl_documents', $item, array('id' => $id));
} else {
$this->db->insert('tbl_documents', $item);
}
$this->db->trans_complete();
return $this->db->trans_status();
}
Subject Part of View
<div class="form-group">
<label for="subject_id">New Subject</label>
<div class="input-group">
<select class="form-control select2" name="subject_id" id="subject_id" style="width: 100%">
<option value=""> Select a New Subject</option>
<?php
$id = !empty($subjects) ? $subjects->subject_id : '';
foreach ($subjects as $sub) {
$selected = "";
if ($id == $sub->subject_id)
$selected = "selected";
echo "<option value= '$sub->subject_id' $selected>$sub-
>subject_name</option>";
}
?>
</select>
<span class="input-group-addon x" aria-describedby="sizing-addon2"
style="padding: 2px 4px !important;"> <a style="cursor: pointer" id="add-subject"
title="Add New Subject"><i style="color: #337ab7 !important;" class="fa fa-2x fa-plus-
circle"></i></a>
</span>
</div>
</div>
<script type="text/javascript">
$(document).on('click', '#add-subject', function (e) {
e.preventDefault();
bootbox.prompt("Enter New Subject", function (result) {
if (result !== null && result !== '') {
$('#subject_id').append('<option>' + result + '</option>')
.val(result);
$("#subject_id").val(result).trigger("change");
}
});
});
</script>

MySQL SUM returns unexpected value

I've been trying to use SUM() to total up some numeric values in my database, but it seems to be returning unexpected values. Here is the PHP-side for generating the SQL:
public function calcField(string $field, array $weeks)
{
$stmt = $this->conn->prepare('SELECT SUM(`'. $field .'`) AS r FROM `ws` WHERE `week` IN(?);');
$stmt->execute([implode(',', $weeks)]);
return $stmt->fetch(\PDO::FETCH_ASSOC)['r'];
}
Let's give it some example data for you folks at home:
$field = 'revenue';
$weeks = [14,15,16,17,18,19,20,21,22,23,24,25,26];
This returns this value:
4707.92
Without seeing the data, this may have seemed to have worked, but here's the rows for those weeks:
+----+------+------+---------+-------+---------+---------+------+----------+
| id | week | year | revenue | sales | gpm_ave | uploads | pool | sold_ave |
+----+------+------+---------+-------+---------+---------+------+----------+
| 2 | 14 | 2019 | 4707.92 | 292 | 13 | 0 | 1479 | 20 |
| 3 | 15 | 2019 | 4373.32 | 304 | 13 | 0 | 1578 | 19 |
| 4 | 16 | 2019 | 4513.10 | 275 | 14 | 0 | 1460 | 19 |
| 5 | 17 | 2019 | 4944.80 | 336 | 14 | 0 | 1642 | 20 |
| 6 | 18 | 2019 | 4343.87 | 339 | 13 | 0 | 1652 | 21 |
| 7 | 19 | 2019 | 3918.59 | 356 | 14 | 0 | 1419 | 25 |
| 8 | 20 | 2019 | 4091.20 | 247 | 19 | 0 | 1602 | 15 |
| 9 | 21 | 2019 | 4177.22 | 242 | 12 | 0 | 1588 | 15 |
| 10 | 22 | 2019 | 3447.88 | 227 | 18 | 0 | 1585 | 14 |
| 11 | 23 | 2019 | 3334.18 | 216 | 15 | 0 | 1675 | 13 |
| 12 | 24 | 2019 | 4736.15 | 281 | 13 | 0 | 1388 | 20 |
| 13 | 25 | 2019 | 4863.84 | 252 | 12 | 0 | 1465 | 17 |
| 14 | 26 | 2019 | 4465.95 | 281 | 21 | 0 | 1704 | 16 |
+----+------+------+---------+-------+---------+---------+------+----------+
As you can see, the total should be far greater than 4707.92 - and I notice that the first row revenue = 4707.92.
Here's what things get weird, if I add this into the function:
echo 'SELECT SUM(`'. $field .'`) AS r FROM `ws` WHERE `week` IN('. implode(',', $weeks) .');';
Which outputs:
SELECT SUM(revenue) AS r FROM ws WHERE week IN(14,15,16,17,18,19,20,21,22,23,24,25,26);
Copying and pasting this into MySQL CLI returns:
MariaDB [nmn]> SELECT SUM(revenue) AS r FROM ws WHERE week IN(14,15,16,17,18,19,20,21,22,23,24,25,26);
+----------+
| r |
+----------+
| 55918.02 |
+----------+
1 row in set (0.00 sec)
Which, looks a lot more accurate. However, that very same SQL statement returns the first row value rather than summing the column for those weeks.
This function gets triggered by an AJAX script:
$d = new Page\Snapshot\D();
# at the minute only outputting dump of values to see what happens
echo '<pre>'. print_r(
$d->getQuarterlySnapshot(new Page\Snapshot\S(), new App\Core\Date(), $_POST['quarter'], '2019'),
1
). '</pre>';
The function $d->getQuarterlySnapshot function:
public function getQuarterlySnapshot(S $s, Date $date, int $q, string $year)
{
switch($q)
{
case 1:
$start = $year. '-01-01 00:00:00';
$end = $year. '-03-31 23:59:59';
break;
case 2:
$start = $year. '-04-01 00:00:00';
$end = $year. '-06-30 23:59:59';
break;
case 3:
$start = $year. '-07-01 00:00:00';
$end = $year. '-09-30 23:59:59';
break;
case 4:
$start = $year. '-10-01 00:00:00';
$end = $year. '-12-31 23:59:59';
break;
}
$weeks = $date->getWeeksInRange('2019', 'W', $start, $end);
foreach ($weeks as $key => $week){$weeks[$key] = $week[0];}
return [
'rev' => $s->calcField('revenue', $weeks),
'sales' => $s->calcField('sales', $weeks),
'gpm_ave' => $s->calcField('gpm_ave', $weeks),
'ul' => $s->calcField('uploads', $weeks),
'pool' => $s->calcField('pool', $weeks),
'sold_ave' => $s->calcField('sold_ave', $weeks)
];
}
So I don't overwrite the value anywhere (that I can see at least). How do I use SUM() with the IN() conditional?
As pointed out in the comments by #MadhurBhaiya:
Comma separated week_id values is passing as a single string in the query: week_id in ('1,2,3...,15') . MySQL implicitly typecasts this to 1 and thus gets the first row only. You will need to change the query preparation code
Led me to breaking up the single ? into named parameters using a foreach loop:
public function calcField(string $field, array $weeks)
{
$data = [];
$endKey = end(array_keys($weeks));
$sql = 'SELECT SUM(`'. $field .'`) AS r FROM `ws` WHERE `week` IN(';
foreach ($weeks as $key => $week)
{
$sql .= ':field'. $key;
$sql .= ($key !== $endKey ? ',' : '');
$data[':field'. $key] = $week;
}
$sql .= ');';
$stmt = $this->conn->prepare($sql);
$stmt->execute($data);
return $stmt->fetch(\PDO::FETCH_ASSOC)['r'];
}
Now each numeric value is treated individually, which, is getting me the expected value.
Yes, it is showing only first row data in your query because you have mentioned where week IN (1,2,3,4,5,6,7,8,9,10,11,12,13); and your data shows that you have week 13 and 1 to 12 does not exist in your data from IN clause of your query.
You are selecting only the row with week 13, the week 1-12 is not existing in your data. That's why the result of your query is 43.900001525878906
Solution 1:
You might want to change the values in your IN()because you are filtering your data by the column week.
SELECT SUM(`revenue`) as `r` FROM `ws` WHERE `week` IN (13,14,15,16,17,18,19,20,21,22,23,24,25);
Solution 2:
You can change the week in your where clause to id
SELECT SUM(`revenue`) as `r` FROM `ws` WHERE `id` IN (1,2,3,4,5,6,7,8,9,10,11,12,13);

Time Driven Conditional Updates on Google Spreadsheets

I would like to update the given date [reset day] on weekly periods.
During this update if weekly attendance will also reset to 0 and if its value is less than 2 Attendance points will decrease by 8 points.
Example Initial Sheet
Name | Attendance Point | Weekly Attendance | Reset Day
--------------------------------------------------------------
Jack | 12 | 0 | 13/09/2018
Jacob | 23 | 0 |
Emily | 12 | 1 |
Rick | 11 | 2 |
Rob | 21 | 3 |
Desired Update
Name | Attendance Point | Weekly Attendance | Reset Day
--------------------------------------------------------------
Jack | 4 | 0 | 20/09/2018
Jacob | 15 | 0 |
Emily | 4 | 0 |
Rick | 11 | 0 |
Rob | 21 | 0 |
Sample base sheet
https://docs.google.com/spreadsheets/d/1khPC5r2p0b1srsEGka3fl-GAl6nHACaVR0Cf31cqA1o/edit?usp=sharing
Thanks in advance
function resetCells() {
var ss = SpreadsheetApp.getActive().getSheetByName('Sheet');
var range = ss.getDataRange().offset(1, 0, ss.getLastRow() - 1);
var values = range.getValues().map(function(e) {
return e[0] ? [false, e[1], e[2], e[3], e[4] + 1, e[5]] : e;
});
range.setValues(values);
}
Update Function
function weekDays() {
var ss = SpreadsheetApp.getActive().getSheetByName('Sheet').getRange('F2').setValue(new Date())
}
I solved the problem with this snippet of script
function weekDays() {
var sd = SpreadsheetApp.getActive().getSheetByName('Sheet').getRange('F2').setValue(new Date())
var ss = SpreadsheetApp.getActive().getSheetByName('Sheet');
var range = ss.getDataRange().offset(1, 0, ss.getLastRow() - 1);
var values = range.getValues().map(function(e) {
if (Number(e[4]) < 2 && Number(e[2] >= 8) ) {
return e[1] ? [e[0], e[1], Number(e[2]) - 8, e[3], 0, e[5]] : e;
} else if (Number(e[4]) < 2 && Number(e[2]) < 8) {
return e[1] ? [e[0], e[1], 0, e[3], 0, e[5]] : e;
} else {
return e[1] ? [e[0], e[1], e[2], e[3], 0, e[5]] : e;
}
});
range.setValues(values);
}

How do I insert multiple value if there is only one value in form

I need to know how can I insert or update a value in my DB for a invoice form if the value of the input that I need to save is only one time?
I have a invoice form where I select a product in every row, and finally I have the input(user_id) with the value I need to save with the rest of the inputs
Like per example, I choose in the invoice:
10 tomatoes
5 garlics
2 beans
and finally there is my Id (user_id, not the Id of PRODUCTOS table that is unique)
Id=1
Here is the schema of my table, and how save or update until now:
| cantidad | nombre del producto | Id |
+------------+---------------------+-------+
| 10 | Tomatoes | 1 |
| 5 | garlics | 0 |
| 2 | beans | 0 |
Here what I need to save or update:
| cantidad | nombre del producto | Id |
+------------+---------------------+-------+
| 10 | Tomatoes | 1 |
| 5 | garlics | 1 |
| 2 | beans | 1 |
Here is the code:
$conn->beginTransaction();
$sql = "INSERT INTO PRODUCTOS
(cantidad, nombreProd, Id)
VALUES ";
$insertQuery = array();
$insertData = array();
foreach ($_POST['cantidad'] as $i => $cantidad) {
$insertQuery[] = '(?, ?, ?)';
$insertData[] = $_POST['cantidad'][$i];
$insertData[] = $_POST['nombreProd'][$i];
$insertData[] = $_POST['Id'][$i];
}
if (!empty($insertQuery)) {
$sql .= implode(', ', $insertQuery);
$stmt = $conn->prepare($sql);
$stmt->execute($insertData);
}
$conn->commit();
Thank you
So you have a single userID you want to INSERT for each product record. I can probably provide a better answer if you post the output of print_r($_POST), but basically in your foreach $POST loop, keep the user ID static:
foreach ($_POST['cantidad'] as $i => $cantidad) {
$insertQuery[] = '(?, ?, ?)';
$insertData[] = $_POST['cantidad'][$i];
$insertData[] = $_POST['nombreProd'][$i];
$insertData[] = $_POST['Id']; //OR $insertData[] = $_POST['Id'][0], depending on $_POST array
}