how to simplify this database update query (php) - php

How could I simplify this update instruction? Whenever a client buys an item it will update the sales with 1.
$this->db->query('SELECT amount FROM shop_items WHERE itemid='.$itemid.'');
$new_amount = $item->amount+1;
if(!$this->db->query('UPDATE shop_items SET amount='.$new_amount.' WHERE itemid='.$itemid.'')):
return false;
endif;
Can't I make it more simple so there are less lines, for example:
if(!$this->db->query('UPDATE shop_items SET amount=_current_value_+1 WHERE itemid='.$itemid.'')):
return false;
endif;
is this possible? if not thanks anyway

What about using the following SQL query :
update shop_items
set amount = amount + 1
where itemid = 123
Basically, in just one SQL query, you set the amount to the previous value it had, plus one.
No need for two queries ;-)
Integrating this in your PHP code should give you something that looks like this :
if (!$this->db->query('UPDATE shop_items SET amount=amount+1 WHERE itemid='.$itemid.'')) :
return false;
endif;
Note : I just replaced your _current_value_ by the name of the field that you're working on : amount.

Related

Attendance system using PHP & MySQL

I have an Attendance system in one of my module project using PHP and MySQL, the MySQL table looks something like this:
Now, timetable is used to store the Time Table for classes in a day for a section and which teacher is assigned to it. The student_info table contains general information about students and the section they belong to. The attendancetable is used to record those who are absent using time and student id as primary key.
I could get a count of how many classes were taken in a semester as follows:
SELECT count(*) as total FROM timetable WHERE flag > ? AND semester = ? AND section = ? AND timeid BETWEEN ? AND ?
Then computed how many times a student attended and also calculate the percentage of attendance.
SELECT stu.* ,
(SELECT COUNT(*)
FROM attendancetable att
WHERE att.s_id = stu.class_roll
AND att.semester = ?
AND att.timeid BETWEEN ? AND ? ) AS absent
FROM student_info stu
WHERE stu.section = ?
AND stu.logYear = ?
AND stu.deleted = ?
ORDER BY stu.class_roll
Now, I want to also display a kind of attendance sheet as follows:
I tried SQL Inner Join but didn't get the way I wanted.
I was thinking that the first row can be output form the following query:
SELECT timeid
FROM timetable
WHERE flag > ?
AND semester = ?
AND section = ?
AND timeid BETWEEN ? AND ?
[UPDATE] Found a way to do this, given as an answer, don't know if that's the right way.
Thank You in advance for helping.
I am probably a bit late with my answer, but I have been playing around a bit too and came up with a solution that is largely done within MySql: my solution builds a dynamic SELECT statement that is executed at the end to provide me with the table, having columns spanning a predefined era:
SET #str='SELECT sid';
SELECT #str:=concat(#str,', MAX(CASE tid WHEN ',t_id,
' THEN \'OK\' ELSE \'\' END) d',t_id)
-- start date end date
FROM times WHERE dati BETWEEN '20170810.0000' and '20171022.2359';
SET #str=concat(#str,' FROM att GROUP BY sid');
PREPARE qu FROM #str;
EXECUTE qu;
What still needs to be done is the translation of date Ids in the column headings to proper dates and, likewise, the translation of student Ids into names or univ_roll numbers.
i have also taken the liberty of changing the table layout a little bit: the primary key in the timetable is now just an integer, the actual time is stored separately in another column, providing flexibility in case dates or times might change.
Here is a little rextester demo: http://rextester.com/LPFF99061 (the attendance table has only been filled for the first few dates).
I'm not sure if I should edit the question with these updates. But this is a partial solution that I did come out with. Would be glad if someone could help optimize this more.
So, I started with this piece of code.
SELECT timeid
FROM timetable
WHERE flag > ?
AND semester = ?
AND section = ?
AND timeid BETWEEN ? AND ?
From the above code I could get the dates where classes are taken. Next, I check if a student is present or absent on the dates mentioned as follows:
SELECT attended FROM attendancetable
WHERE s_id = ?
AND semester = ?
AND timeid = ?
With this I was able to see if a student is absent or not. In php it look something like this:
//Getting the dates
$query = "SELECT timeid FROM timetable
WHERE flag > ?
AND semester = ?
AND section = ?
AND timeid BETWEEN ? AND ?";
$params = array(0, 1, 'A', '2017-01-01', '2017-06-30' );
$stmt = $db->prepare($query);
$stmt->execute($params);
$dates = $stmt->fetchall();
//checking if students is present or absent
$query = "SELECT attended FROM attendancetable
WHERE s_id = ?
AND semester = ?
AND timeid = ?";
//Now I'm going to loop through the $dates
foreach($dates as $date){
$params = array(1, 'A', $date['timeid']);
$stmt = $db->prepare($query);
$stmt->execute($params);
$result = $stmt->fetchall();
($result) ? $present = 1 : $present = 0;
}
In the above way, I was able to compute if a student of a particular section is present/absent for a given class as per the timetable. Now, if I want for all the students in a section I could first query the student_info table and then compute the foreach loop for each individual student
SELECT class_roll FROM student_info
WHERE logYear = ?
AND section = ?
AND deleted = ?
ORDER BY class_roll LIMIT ?, ?
Each student is then run through the foreach loop to check if they are absent or present. Finally, I could get this:
I tested the execution time locally for about 200 students it came to about 1.6 seconds when the number of classes is only 39. I do test from previous data also for a whole semester and the code exceed 30 seconds and max_execution_time error triggered. As of now, I set a 25 number of students limits per page.
UPDATE: The max_execution_time error seems to appear only on the first run, but later when I try to re-produce its not giving anymore error and the time taken to complete the task is below 2 seconds.

MYSQL : SET value in an UPDATE query when all conditions of subquery are satisfied

Problem
There are 2 tables DEALS and DEAL_DETAILS.
DEALS table contains title and other generic information about the deal.
DEAL_DETAILS table contains information on different time ranges at which deal has to be shown, address specific to deal etc.,
I have abstracted the columns we need to focus on and have attached the schema below.
What I need to achieve is-
When ALL status-es of a particular dealid in DEAL_DETAILS is 'completed' I would like to update the status in DEALS table as 'completed'.
Giving an example-
The status of 1013 in DEALS table should be 'completed'. As ALL statuses of 1013 linked(Foreign Key) dealid in DEAL_DETAILS are in 'completed' status.
Whereas, that's not the case with 1012 as 2 are in 'completed' status and other 2 have different status. So, status in DEALS table should NOT be changed.
And, 1011 is out of question!
My schema looks like this-
DEALS:
DEAL_DETAILS:
I did try some SQL queries by referring to this, this, this and this. My query is incomplete and doesn't look good.
Currently, I have achieved the same inefficiently(I guess) using PHP(please ignore if there are change in column names).
while ($row = mysqli_fetch_assoc($aggregateStatusresult)) {
//$return_array[$i++] = $row;
if(strcmp($row->status, 'completed') && (!(isset($statusarray[$row->dealid])) || ($statusarray[$row->dealid] != 'completed')))
$statusarray[$row->dealid] = 'completed';
else
$statusarray[$row->dealid] = $row->status;
}
foreach($statusarray as $dealid => $status){
$updateAggregateStatus = "update deals d set d.status='".$status."' where d.dealid = '".$dealid."'";
$updateAggregateStatusresult = $connection->query($updateAggregateStatus);
}
You should be able to handle it with a simple NOT EXISTS check:
UPDATE deals d SET d.status='approved'
WHERE NOT EXISTS (SELECT * FROM deal_details
WHERE deal_details.dealid = d.id AND status <> 'completed');
This assumes there are always rows in the deal_details table, if there are none it will mark the deal approved.

Subtraction in SQL statement for stock

A database lists items and their stock count. When someone buys items I wish to update the stock count in the database.
Regardless of the following subtraction f_item_number = f_item_number - $mugAmount, my update statement isn't working.
If I have 200 mugs in the database. When I run the following statement the new mug amount is listed incorrectly afterwards as -1. Rather than the expected value of 199. Why is this?
DB::update('UPDATE `shop_items` SET `f_item_number` = ? WHERE `f_item_name` = ?', array(`f_item_number` - $mugAmount, "mug"));
You can't pass in database column text in the parameters. Try this
DB::update('UPDATE `shop_items` SET `f_item_number` = `f_item_number` - ? WHERE `f_item_name` = ?', array($mugAmount, "mug"));

php adding amount in rows

I want to add the rows that is being query in database. There is an amount paid, previous balance, new balance.. I want the previous balance to be added by paid amount.
Num|pay|old|new
1 |100|500|600
2 |120|600|720
3 |200|720|920
4 |300|720|920
5 |350|720|920
6 |500|720|920
The database query has data of amountPaid (pay), previous balance (old), new balance (new), but the data in column(new) is wrong.I want to correct it in forloop.Is there a way to help me in this? to get the column(new) value is
column(pay)100 + column(old)500 = column(new)600.
the column(new) in number two will be put in column(old)600 then added by column(pay)120 is equal to column(new)720 and so on.
Hope you can help me in this...
I suppose you are adding the amounts when user submits it
1) Use mysql UPDATE clause in order to change the value in the coloumns
2) use while loop to get the previous value selecting it with a specific id which I suppose you have in your table
3) add it with a new value and update the new amount coloumn
PHP
<?php
$id=$_POST['id'];
$amount=$_POST['amount'];
include("connection.php");
$sql="SELECT * FROM `tablename` WHERE `user_id` ='$id'";
$res=mysql_query($sql);
$row=mysql_fetch_array($res){
$t2 = $row['previous_amount'];
$t3=$t2+$amount;
$sql="UPDATE `bank`.`tablename` SET `new_amount' = '$t3'";
}
?>

How does if else work?

How do i start on an if else statement to restrict?
Fields in database :
No_of_vacancy (shows the number of positions available in the company)
Assigned (shows the number of student assigned to company)
EG
ABC Co
No of vancacy = 2
Assigned student = 2
I have done the necessary statement
UPDATE job_details,
student_details
SET
assigned = assigned + 1
WHERE
student_details.jobscope1 = job_details.jobscope
AND student_details.jobscope1 = 'IT';
The above statement works fine. meaning each time query runs. 1 student will be added under assigned field in database. I want the query to stop after assigned field matches the no of vacancy field to avoid duplication.
My logic is that i have to use if else statement to restrict the amount of assigned students from going over the no of vacancy available which is 2.
how do i start?
And if you simply add, to the where, and (assigned + 1) < job_details.No_of_vacancy ?

Categories