Performing update slots for timeslots table using mysql database - php

I am doing a booking cancellation function. I have successfully removed the data in reservation table as shown in the code below. However, I would like to update the status for the timeslots. For the timeslots table, 1 = not available for booking anymore, 0 = available for booking. While the user logs in into the account, they can view the appointment and perform booking cancellation, which is where I am stuck with on updating the timeslots to make it available for booking again.
For the reservations table, its status means visited or not visited, which is not related to this question. However, the reservation table is the table which shows the information to the users to view their appointment history, and here is where the cancellation feature will be provided, using a button.
The problem is that I do not know how to connect between the reservation table and the timeslot table. I need the timeslot table to show the updated status is 0 after cancellation happens for a particular day instead of continue showing 1. Below I will attach the database in SQL and the codes implemented.
Timeslots database:
Reservations database:
Below is the sample code of making an appointment, which has been implemented successfully.
public function store(Request $request){
date_default_timezone_set('Asia/Kuala_Lumpur');
$request->validate(['time'=>'required']);
$check = $this->checkBookingTimeInterval();
}
Reservation::create([
'user_id'=>auth()->user()->id,
'dentist_id'=>$request->dentistId,
'time'=> $request->time,
'date'=> $request->date,
'status'=>0
]);
Timeslot::where('appointment_id', $request->appointmentId)
->where('time', $request->time)
->update(['status'=>1]);
I want add cancel booking, however, I do not know how to update the timeslots status to become zero from timeslots database (0 means the timeslots is available for booking again). The reservation database has been deleted when I want to perform cancel booking, just as what I want.
public function destroy($id,Request $request){
//delete reservation in records
$reservation = Reservation::find($id);
$reservationDelete = $reservation->delete();
//how to update the timeslots status to become 0 from timeslots database?
return redirect()->route('my.appointment')->with('message', 'Appointment has been cancelled successfully');
}

Related

How to perform update slots from 2 sql tables?

I am doing a booking cancellation function. I have successfully removed the data in reservation table as shown in the code below. However, I would like to update the status for the timeslots. For the timeslots table, 1 = not available for booking anymore, 0 = available for booking. While the user logs in into the account, they can view the appointment and perform booking cancellation, which is where I am stuck with on updating the timeslots to make it available for booking again.
For the reservations table, its status means visited or not visited, which is not related to this question. However, the reservation table is the table which shows the information to the users to view their appointment history, and here is where the cancellation feature will be provided, using a button.
The problem is that I do not know how to connect between the reservation table and the timeslot table. I need the timeslot table to show the updated status is 0 after cancellation happens for a particular day instead of continue showing 1. Below I will attach the database in SQL and the codes implemented.
Timeslots database:
Reservations database:
public function destroy($id,Request $request){
//delete reservation in records
$reservation = Reservation::find($id);
$reservationDelete = $reservation->delete();
//how to update the timeslots status to become 0 from timeslots database?
return redirect()->route('my.appointment')->with('message', 'Appointment has been cancelled successfully');
}
Maybe you should use MySQL transaction to do this both modification in 1 transaction.
I recommend to use 2 different query in 1 transaction.
Your description about this problem is not fully clear, sorry for misunderstand.

Calculate total due in php codigniter

I have a small billing software written in php CodeIgniter. This is how i save values when i submit a payment
<?php
public function addPayment() {
$id = $this->input->post('id');
$client_id = $this->input->post('client_id');
$date = strtotime($this->input->post('date_from_addpayment'));
$description = $this->input->post('description');
$cash_pending = $this->input->post('cash_pending');
$cash_recevied = $this->input->post('cash_recevied');
$balance = $cash_pending - $cash_recevied;
?>
When each transaction occur I want to sum all the due of the client at that time and save it in balance table in MySQL.
My PHPMySQL structure of payment column is as follow:
https://i.stack.imgur.com/ELJrL.png
I just want when user ADD THE PAYMENT then balance due at that time display in this column.
Screenshot: https://i.imgur.com/raboF4M.png
To my understanding, balance, due, cash_pending - all 3 field relates - refers to the same figure - the amount that is pending. What i believe is you need to restructure the code for a bit.
You need to have a table maintaining clients balance (like current one you have). Just u can remove cash_pending / due fields.
You then need to have another table that will record in transactions of all the cash received. And as and when the cash is received, you can just substract that amount from the balance for the client.
In case any excess amount needs to be added for something like cash given or so - that you can add to the clients balance field back. So all the time - you have a proper balance figure for the client and also have a record of all the cash received from the user.
First of all before ending the php tag close your function's curly bracket.
In your table id is auto increment so do not need to take id as a input to store in database.
put all required fields as your table structure like this.
$data = array('client_id'=>$client_id, 'date'=>$date,
'description'=>$description, 'cash_recevied'=>$cash_recevied, 'cash_pending'=>$cash_pending,
'due'=>$due );
$this->load->model('Your-model-name');
$this->your-model-name->function-name($data);
Now call your model. and then in your model do this
function FunctionName($data){
return $this->db->insert('tablename', $data);
}

Approval And Rejection For Multiuser

We Have a table of approval like below:
In above table we have ApprovalId and ApprovalLevel like first level approval and second level approval in ApprovalLevel (For Approving Approval by its level).
I am trying to fetch record in query if specific user ApprovalLevel >= 1 then check its previous ApprovalStatus if it Approved then show its record too.
I have tried many things but still not getting specify record.
In Simple term select record with User if only if its ApprovalLevel=1 or its previous ApprovalLevel ApprovalStatus=1.
Please help me on this: [IN this table ApprovalStatus: 0 = Pending and 1:Approved]
I believe this is what you are requesting:
SELECT
ApprovalStatus,
ApprovalLevel,
CreatedOn
FROM
approval
WHERE
ApprovalLevel = 1
OR (ApprovalLevel > 1 AND ApprovalStatus = 1)
;

Prevent race condition and lock tables in hotel booking system PHP/MySQL

I am building a hotel style reservation system and I am loosing the way. I've got stuck at the exactly reservation moment when to add the reservation and I am concerned about come situations.
My flow is really easy, it lets multiple user to go through the reservation process for the same room until one of them press the reservation button before the others. The reservation information is kept in the session and is never stored in the db until somebody reach last step and press "book". In every step, the system check if the room/s is/are available if not it gives the error page.
Now the problem is preventing race condition combined to a last one mandatory check if still there are enough rooms left:
When user is in last step, he/she select the payment method and press book button. After checking if the selected payment option is ok (form data hasn't been altered) it redirects to the reservation controller where:
reservation controller
<?php
ReservationController extends JControllerLegacy{
public function placeReservation(){
//Do some checks to prevent direct access, booking existence and user completed all steps
$reservatioModel = $this ->getModel('Reservation')
if(!$reservationModel->placeReservation()){
//set errors and redirect to error page
return false;
}
//booking had been placed, passes the data to payment plugin
}
?>
and
Reservation model:
<?php
ReservationModel extends JModelLegacy{
public function placeReservation(){
//Get all variables and objects
//Lock the tables to prevent any insert while the last check
$db ->lockTable(#__bookings);
$db ->lockTable(#__booking_room);
//Perform the last mandatory check with tables locked to prevent read the table right one moment before another transaction insert the booking and allowing overbooking. THIS CHECK MUST BE 100% SURE NO ONE ELSE IS MANIPULATING/READING THE TABLE
if(!$this ->checkRoomsAvailability($data))
return false;
try{
$db ->transactionStart();
//Add the reservation in the booking table
if(!$this ->_saveBooking()){
$db ->rollBack();
return false;
}
//Add the room/s to the middle table #__booking_room
if(!$this -> _saveRooms())
$db ->rollBack();
return false;
}
$db ->transactionCommit();
}catch(Exception $e){
$db ->rollBack();
$this ->setError('We were not able to complete your reservation.');
return false;
}
$db ->unlockTables();
}
?>
The above mentioned tables are InnoDB, #__bookings hold the bookings and #__booking_room hold the information for the selected rooms (like avg_price, number of rooms, etc) and it has an foreign key to #__rooms and one to #__bookings
What am I concerned about?
1 - I am using other tables during the last availability check than the two locked and is giving me error.
2 - When the second user's execution arrives at the table locking point, does it wait until they get free or does it raise an error/exception? I could catch the exception and redirect user to the error page but locket table doesn't means reservation placed, it can occurs any issue while saving the information.
I hope my workflow is ok, please let me know if I am good to go or I should improve my code.
Thanks
EDIT:
To be mentioned, the business idea is like i.e. Expedia, booking, etc where you are allowed to select more rooms types and units per reservation. Indeed, my room table is not for specific/real room but is meant to be for room type with a fixed number of units available everyday if not already booked.
My approach would be simpler. In the table that stores the actual reservation, I would have a foreign key for the specific room being reserved, and have a UNIQUE index for the fields roomID, date. This will ensure that the same roomID cannot be recorded twice for the same date.
Next, when the customer confirms booking, I would run everything in a transaction as you're currently doing. When the code gets to the last place and tries to insert a new reservation, if a moment before another customer reserved that room, the DB will not allow you to insert another reservation for that room for that date. That's when I would either:
rollback and throw the error, or
try again with another room (with its own roomID) if there is another room of the same type still available
I can not say if your workflow aka business domain is the right choice as it depends on your business. But technically you want to have a booking transaction which also provides a check against double booking. The easiest way could be a room-booking-dates table with unique constraint on room is and date. So during your booking transaction you also insert each day with the room id into the table and the unique constraint will ensure that the second attempt will fail.
PS: If a table is locked, PHP will just wait for the unlock. No exception will be thrown (at least if the connection does not close after x seconds)

Laravel - error saving record with one to many relationship

Struggling to update my code with laravel relationships.
I have two tables. Customer and Reservations with Customer having a hasMany relationship with Reservation and Reservation having a belongs to relationship with Customer.
The reservation table also has a many to many relationship with a product table via a link table.
I obtain the customer record ok and I now need to create a reservation for the customer.
I'm assuming the process is:
create the reservation object, attach the reservation to the customer and then link to the product. (the reservation table has a few relationships but I'll get this working for now)
If I try this code I get an error Field 'customer_id' doesn't have a default value - the database table allows null and there are no validation rules set so assume this is to do with the relationship I've set up.
`$reservation = new Reservation;
$reservation->play_date=$play_date->format('Y-m-d');
$reservation->booked_date=$booked_date->format('Y-m-d');
$reservation->am_tee=$am_time->format('H:i:s');
$reservation->pm_tee=$pm_time->format('H:i:s');
$reservation->save();
$customer->reservation()->associate($reservation);`
The error occurs with $reservation->save();
I then need to use the created $reservation to create entries in the product link table so need to be able to access the newly created reservation and it's relationship with products.
I can create the entry using $customer->reservation()->save($reservation); but then I don't seem to have a $reservation object to work with (or do I?)
I'm very confused by the relationships so grateful for all help to understand how to get this to work
Thanks
here's my relationships in the models:
Customer Class:
public function reservation() {
return $this->hasMany('Reservation');
}
Reservation Class:
public function customer() {
return $this->belongsTo('Customer');
}
The only method that appears to work is $customer->reservation()->save($reservation); - so I assume this is the correct method and will have to rework my code. associate()
update: recreated my table in mysql - I can now save the original reservation record as expected and then associate to the customer record using:
$reservation->customer()->associate($customer)
This is taking a while for it to sink in with me!
PART 1
since Customer hasMany Reservations, you need the customer id before you can add a reservation.
on your code,
you need to get the customer first that owns the reservation
$customer = Customer::find($id);
now,
$reservation = new Reservation;
$reservation->customer_id = $customer->id;
$reservation->play_date=$play_date->format('Y-m-d');
$reservation->booked_date=$booked_date->format('Y-m-d');
$reservation->am_tee=$am_time->format('H:i:s');
$reservation->pm_tee=$pm_time->format('H:i:s');
$reservation->save();
then, the $reservation->save(); should succeed now.
PART 2
on your question:
"I can create the entry using $customer->reservation()->save($reservation); but then I don't seem to have a $reservation object to work with (or do I?)"
you can get all reservations of a customer by using
$reservations = $customer->reservation->get();
//where customer is the one you had on Customer::find($id);
you can then loop on the reservations one by one. (although i think you might want the reservation ids, so the first approach above is better)

Categories