How to update database values for a whole day - php

I am building a web application, for travelling. I have managed to get users to be able to insert how much they have spent on each category (i.e. travel, accomodation, food, etc) into the database once from a form. However, I want them to be able to contiously add to the total value of each category for just that day using the same form, and then everyday have a new total for each category as well.
I'm not quite sure how I would do that at the moment.
Here is my code so far for inserting the values into the database from my form (which works):
if(isset($_POST['addinfo_button'])){
$Food = $_POST['food'];
$Transport = $_POST['transport'];
$Accom = $_POST['accomodation'];
$Entertain = $_POST['entertainment'];
$Souvenir = $_POST['souvenirs'];
$Misc = $_POST['miscellaneous'];
$Date = date("Y-m-d");
$Trip_id;
$sql = "SELECT * FROM trips WHERE id =$user_id_session AND date1 <= '$Date' && date2 >= '$Date'";
$records = mysql_query($sql);
while($trip=mysql_fetch_assoc($records)){
$Trip_id = $trip['trip_id'];
}
$foreignkey = $user_info['id'];
$sql = $con->query("INSERT INTO todays_spend (food, transport, accomodation, entertainment, souvenirs, miscellaneous,date, trip_id, id)Values('{$Food}', '{$Transport}', '{$Accom}', '{$Entertain}','{$Souvenir}', '{$Misc}','{$Date}','{$Trip_id}','{$foreignkey}')");
header('Location: budgetbuddy.php');
}
Would I have to do something similar to this? or modify this one slightly?

Could not write code for you. But I can give you an Idea how you can achieve this having only one form.
Create a table with your needs.I mean your entertainement, food, etc along with their name and Id. If you can make user enter their name or anything that users can uniquely identified. Then things go easier. When a user enter their how much they spent insert into table along with their name or identifier. Next time same user enter details simply find if already user has anything updated on same day , if user added anything before simply update the table by adding previously existing values to new values. Update them. Now you easily even find how much each user spent on particuler catogery.Hope it helps. Thank you.

Related

Select all rows from one table and one specific value for each row from another table

Good afternoon lads, I am trying to make a page where I can check which bosses I did today. I have two tables (table with bosses and table with boss times). Now I need to show all bosses but for each of them I only want to show the closest time when the boss is going to spawn.
The select so far looks like that:
$timePlus = strtotime($currentTime) + 60*60*2.2;
$timePlusForm = date("H:i:s", $timePlus);
$userNametoLower = strtolower($userName);
$userTableName = "".$userNametoLower."_bosses";
$currentTime = date("H:i:s", time());
"SELECT `bossTime`.`ID`, `bossTime`.`bossID`, `bossTime`.`time`, `$userTableName`.`ID`, `$userTableName`.`name`,
`$userTableName`.`zone`, `$userTableName`.`map`, `$userTableName`.`waypointCode`, `$userTableName`.`bossDone`
FROM `bossTime` LEFT JOIN `$userTableName` ON `$userTableName`.`ID` = `bossTime`.`bossID`
WHERE `bossTime`.`time` BETWEEN '$currentTime' AND '$timePlusForm'
GROUP BY `bossTime`.`bossID`
ORDER BY `bossTime`.`time` ASC";
The problem is that this select does not pick the next closest value from time table. I also tried BETWEEN and it also didn't work (some bosses got correct closest time but other got the second closest). Any idea how to solve this is welcomed.
I removed GROUP BY and changed the condition to WHERE bossTime.time >= '$currentTime' AND bossTime.time <='$timePlusForm' and for some reason it works

SQL UPDATE query fails to update some of the time - PHP Booking System

I've built a simple booking system using SQL, php, and Javascript/Jquery. I'm also using AJAX. The idea is that the user is presented with a list of available timeslots and when the user selects one that chosen timeslot should automatically disappear (the available timeslots reload again via AJAX) and so become unavailable to further users. Each timeslot is output as an html td element containing a link which stores the timeslot 'id' (as set in the database) as an attribute of that hyperlink. When the timeslot is clicked, the timeslot id is sent to the php function below using AJAX. Timeslots are displayed according to whether their visibility column is zero or one as stored in the database.
I am testing this with quite a large group of users and I've noticed that every so often (maybe once every twenty or thirty bookings) the SQL UPDATE query responsible for updating the timeslot availability value to zero does not seem to be doing what it should, and the value remains at one, thus resulting in an occasional double booking.
Otherwise, everything works absolutely fine - I've tested the application with my colleagues as much as I can and I'm unable to replicate the problem, double bookings obviously aren't an option though. Might anyone have an idea of what could be going wrong?
Thanks in advance for any suggestions/help.
public function makebooking($user, $timeslotUID, $timeslot, $edits) {
$username = $user->username;
$user_fn = $user->displayname;
$plgID = $user->plg; //The 'PLG' is the person who the user is booking an appointment with
$user = $edits['user'];
$currentDate = $edits['date'];
$json = new JSON();
$json->user = stripslashes($user);
$json->currentDate = $currentDate;
//Problem seems to occur here..
$q1 = " UPDATE plg_timeslots
SET visible = 0
WHERE id= '$timeslotUID';" ;
$res1 = $this->dbcon->query($q1);
//If the user already has a booking they are rearranging
$currentBooking = $this->getBookings($username, 'STU');
if($currentBooking) {
//Reinstate previous timeslot
$q2 = "UPDATE plg_timeslots
SET visible = 1
WHERE id= '$timeslotUID';" ;
$res2 = $this->dbcon->query($q2);
//Update current booking
$q3 = "UPDATE bookings
SET timeslot_id = '$timeslotUID',
timeslot = '$timeslot',
edited_by = '$user',
edited_when = '$currentDate'
WHERE user_id = '$username' ;";
$res3 = $this->dbcon->query($q3);
} else { //If no booking is present, make a new booking
$q4 = "INSERT INTO bookings (plg_id, user_id, timeslot_id, timeslot,
edited_by, user_fn, edited_when)
VALUES ('$plgId', '$username' ,'$timeslotUID',
'$timeslot', '$user', '$user_fn',
'$currentDate');";
$res4 = $this->dbcon->query($q4);
}
return $json;
}

MYSQL need help pulling data from each "user" using php

Here's what I have. This code grabs the data from all of the users and subtracts 1 from user_days then updates every user's user_days row.
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
$minusone = $row['user_days']-1;
mysqli_query($con,"UPDATE users SET user_days=$minusone");
echo "<br />";
echo $row['user_days'];
}
The problem I'm having is this:
Instead of subtracting 1 from each user and updating each users field,
it's updating each user's field with the value from the first user.
example:
before updating
user 1 has 30 days
user 2 has 60 days
after updating
user 1 has 29 days
user 2 has 29 days (instead of 59 days)
Any help is appreciated and I hope this question is easy to understand.
Just to clarify, I DO want to update every field.
I just don't want the updates to be duplicated from the first result.
Thanks for all of the answers, this has given me a lot of help.
Why don't you just run UPDATE users SET user_days = user_days-1 WHERE id=XXXXX? And then select the whole thing?
When you update your record, you need to specify the user id for the record of interest, otherwise you current query updates all the rows in your table.
You should point which record to UPDATE
mysqli_query($con,"UPDATE users SET user_days=$minusone WHERE id=XXXXX");
The problem is with the UPDATE statement. Without a WHERE clause it will apply the SET clause to every row in the database. Assuming you have a unique id column named id in the users table, you could modify your code like this:
while($row = mysqli_fetch_array($result))
{
$minusone = $row['user_days']-1;
$user_id = $row['id'];
mysqli_query($con,"UPDATE users SET user_days=$minusone WHERE id=$user_id");
echo "<br />";
echo $row['user_days'];
}
Use the following Query:
mysqli_query($con,"UPDATE users SET user_days=$minusone WHERE user_ID = '".$row['user_ID']."'");
You're updating all the users with the same $minusone value. You need a WHERE clause in your update statement, like this:
$result = mysqli_query($con,"SELECT * FROM users");
while($row = mysqli_fetch_array($result))
{
$minusone = $row['user_days']-1;
$id_user = $row['id_user'];
mysqli_query($con,"UPDATE users SET user_days=$minusone WHERE id_user = $id_user");
echo "<br />";
echo $row['user_days'];
}
Another way of doing what you want would be:
...
$result = mysqli_query($con,"UPDATE users SET user_days = user_days - 1");
...
This assuming you want to substracts 1 to all user_days.
As already pointed out by other answers, the best way to do this is to replace your entire code block with one line.
mysqli_query($con, "UPDATE users SET user_days=user_days-1");
Then you can SELECT and display the information as needed.
Without knowing exactly what you are using user_days for, I'm thinking there may be a better approach to what you are trying to do. I am assuming this is some kind of subscription service, and this code will be run once per day to decrement the number of days to allow them to access the service.
A better approach would be to have a subscriptionExpires field in your database, which would hold a datetime value. Using your approach, if the job that runs this fails, every user will get an extra day. What if a web spider or a user finds your script, your users accounts will expire early. If you use an actual date for when the account expires, there's no guessing if the current value is correct.

variable values conflicts with multiple user

Iam new to PHP, trying to do personalized search engine it works fine with the single user... but simultaneously 2 user uses.. the values in the Variable showing wrong values.
Eg:
if user1 search "Apple" then $qry="Apple", same time user2 search "orange" then $qry="orange" that time the user1 will get the remaining stuffs related "orange".
function storewords($str,$id)
{
$words= str_word_count($str,1);
$cntstr = count($words);
//echo $cntstr;
for($i=0;$i<$cntstr;$i++)
{
$allwords= $words[$i];
$insert = "INSERT INTO freq (word,extra) VALUES ('".$allwords."','".$id."')";
$add_member = mysql_query($insert);
}
}
Which i have process of preprocessing, extracting concept for each user's content.. each user have different content.
I think i have expressed my doubt in correct word, if no please excuse. Please help me, Thanks in advance
You just have to store user id somehow, to get separate "searches" for each user later.
$insert = "INSERT INTO freq (userid,word,extra) VALUES (...)";
Then you should select from that table using SELECT with filter like this: "WHERE userid=$current_user_id"

Relational MySQL - fetched properties?

I'm currently using the following PHP code:
// Get all subordinates
$subords = array();
$supervisorID = $this->session->userdata('supervisor_id');
$result = $this->db->query(sprintf("SELECT * FROM users WHERE supervisor_id=%d AND id!=%d",$supervisorID, $supervisorID));
$user_list_query = 'user_id='.$supervisorID;
foreach($result->result() as $user){
$user_list_query .= ' OR user_id='.$user->id;
$subords[$user->id] = $user;
}
// Get Submissions
$submissionsResult = $this->db->query(sprintf("SELECT * FROM submissions WHERE %s", $user_list_query));
$submissions = array();
foreach($submissionsResult->result() as $submission){
$entriesResult = $this->db->query(sprintf("SELECT * FROM submittedentries WHERE timestamp=%d", $submission->timestamp));
$entries = array();
foreach($entriesResult->result() as $entries) $entries[] = $entry;
$submissions[] = array(
'user' => $subords[$submission->user_id],
'entries' => $entries
);
$entriesResult->free_result();
}
Basically I'm getting a list of users that are subordinates of a given supervisor_id (every user entry has a supervisor_id field), then grabbing entries belonging to any of those users.
I can't help but think there is a more elegant way of doing this, like SELECT FROM tablename where user->supervisor_id=2222
Is there something like this with PHP/MySQL?
Should probably learn relational databases properly sometime. :(
EDIT:
here is the relevant schema
submissions
===============================
id, user_id, timestamp
submittedentries
===============================
id, user_id, timestamp
users
===============================
id, supervisor_id, email
one submission has many submittedentries, and currently I'm referencing this by using the timestamp. I'd be more than willing to alter this if someone can suggest a more efficient way. (and yes, there are more fields that I'm omitting)
This should, if I got the column names correct, get a list of submissions from users who have the specified supervisor.
SELECT * FROM users, submissions
WHERE users.supervisor_id = $supervisorID
AND submissions.user_id = users.id
This version attempts to combine the timestamp checking as well.
SELECT * FROM users, submissions, submittedentries
WHERE users.supervisor_id = $supervisorID
AND submissions.user_id = users.id
AND submittedentries.timestamp = submissions.timestamp
Edit: Updated to match the additional table info. I'm still not 100% sure that the second version is correct, will need to be tested against the database to find out :)
Oh, and in practice you should probably replace the asterisk with the names of the actual columns you want to retrieve.

Categories