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.
Related
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.
I have a field on my website, which updates a value in my mysql database. I want to make it so the user can only update the value every 3 days. How would I go about doing this?
Here is the code that I have written so far:
<?php
if(isset($_POST['Update'])){
$UpdateHWID = $_POST['HWID'];
$sql = $con->query("UPDATE users SET HWID = '{$UpdateHWID}' where UserID = $User");
echo "HWID Updated Successfully!";
}
?>
Use a last updated field in mysql (date and time of last update), and check it before making the update. If satisfies your condition then commit the update and also update that time field, if not show error to the user.
Create new row into db (last_update) type= data
//return to sql last_update (select db ...)
$current_Data = date ('Y-m-d');
$current_Data_time = strtotime ($current_Data); //convert data to time
$last_update_p3 = strtotime ("+3day", strtotime($last_update));
$last_update_p3 = strtotime ($last_update_p3);//convert data to time
if($current_Data_time <=$last_update_p3)
{
$sql = $con->query("UPDATE users SET HWID = '{$UpdateHWID}' , last_update='{$current_Data}' where UserID = $User");
//update last data with current date
}
else
{
//It has not gone three days
}
According to Pinx0, if you add a new column to your users table which contains the date of the last update, then you can create a condition. For example:
ALTER TABLE `users`
ADD `lastUpdated` DATE NOT NULL;
Now you can add a condition to your existing query something like this:
UPDATE `users`
SET `HWID` = '{$UpdateHWID}',
`lastUpdated` = NOW()
WHERE `UserID` = $User AND 2 < DATEDIFF(CURDATE(),`lastUpdated`);
You can easily do that, using the DATEDIFF method.
It will be my first comment. so, Let me know if I have written
something incorrectly here.
$currentDate = date('Y-m-d');
$query = "SELECT DATEDIFF($currentDate,*Last_update_date_row_name*) as diff FROM *TABLE_NAME* WHERE user_id=Current_User_Id";
$result = mysqli_query($conn,$query);
if($result!=false){
//compare the diff with your desire number
// then you can hide or disable the button or show error
}
I have a php script that displays records from a database. It's probably not the best script, as I'm very new to php.
I've added an additional column in my table and would like to keep a count in that column to show me how many times each of the records have been viewed.
Heres the part of the code I think i need to add the code to... if i need to post the entire page i will, but i just figured i could add the line to this part.
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
}
the new column name is 'views' and i just want to add 1 to it each time a record from the database is viewed.
any help greatly appreciated.
Add a new field views to the table.
When, user views the page, fire the SQL.
$query = "UPDATE offers SET views = views + 1";
mysqli_query($con,"update offers set views = views + 1");
If you have added the column, it probably has a NULL value. Either set the value to 0, by doing:
update offers
set views = 0;
Or use:
update offers
set views = coalesce(views, 0) + 1;
You can change your code with this rewritten code assuming that your Table has a column views (datatype int).
//Get the details from previous page
$SelectedCounty = $_POST["result"];
//set variable for next SEARCH
$option = '';
// Get the county names from database - no duplicates - Order A-Z
$query = "SELECT DISTINCT tradingCounty FROM offers ORDER BY tradingCounty ASC";
// execute the query, $result will hold all of the Counties in an array
$result = mysqli_query($con,$query);
if($result){
$query2 = "UPDATE offers SET views=views+1;
mysqli_query($con,$query2);
}
while($row = mysqli_fetch_array($result)) {
$option .="<option>" . $row['tradingCounty'] . "</option>";
}
Or if you need to track the view counts for individual records, you need to modify your code a bit. And probably you need to add one more field in the database for eg. id (datatype int) which can distinguish between different records.
Please clear your problem properly.
As far as i have analysed your code it brings out the following case.
There are different records for tradingConty, and whenever a user views that particular record(one of the tradingCounty record) by clicking that or any other action specified, the php script is set to increament the view count for that particular entry(we can get that by id) in the database.
If thats the scenario, we can easily generate a code accordingly.
I almost finished a site which stores and lets admins manipulate user information.
The last function I implemented was the ability to modify rankings: every user has a rank, and you can use a menu to manually adjust it by moving users up or down.
It works perfectly: I can modify it, the database stores the new rankings correctly; I can add a new user and it becomes the lowest ranked one. The problem is when I try to delete a user.
I wrote a PHP script, which should do the following:
Receive the user's ID
Remove the user's data from two table by using a WHERE statement
Remove the user's uploaded file from the server
Update the other users' rank, so if I deleted the 3rd user, the previously 4th becomes the 3rd, the 5th will be the new 4th and so on. This last part is where my code doesn't work.
Here is the whole PHP:
<?php
// Connecting to the server.
$con=mysqli_connect("connection data");
$rangcounter = 1;
//deleting the user's data - works: the user's data is deleted from both tables
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$id = $_POST['playerid'];
mysqli_query($con,"DELETE FROM Player WHERE ID=$id");
mysqli_query($con,"DELETE FROM Troops WHERE ID=$id");
}
//deleting the user's image from the server - works: the user's file is deleted
$directory = 'uploads/';
unlink($directory . $id . "picture.jpg");
//updating the database - does not work: the other users' ranks stay the same as before
$result = mysqli_query($con,"SELECT * FROM Player ORDER BY rank ASC");
while($row = mysqli_fetch_array($result)) {
$updateid = $row['ID'];
mysqli_query($con,"UPDATE Player SET 'rank' = $rangcounter WHERE ID='$updateid'");
$rangcounter++; //this variable should always be correctly high rank for any given loop. This way I can remove the highest ranked user (1st), then set every other one's rank to one less: the previously 2nd becomes the new 1st (when `$rangcounter` is 1); the previous 3rd will be the new 2nd (when `$rangcounter` is 2), and so on for every row.
}
header("redirect to main page");
exit();
?>
My idea was to create a new variable, which starts at 1, then, with every UPDATE I increment it. Because $result is ordered by the rank, it shouldn't be a problem, right? But it does not work, and I'm fairly sure it's because of a simple reason, but I just can't put my finger on it.
Could any of you help?
Update: TJ- solved it: MySQL update in a PHP While loop
Add quotes '' around $rangcounter in your mysqli_query.
mysqli_query($con,"UPDATE Player SET 'rank' = '$rangcounter' WHERE ID='$updateid'");
Hope this helps you
Change to
mysqli_query($con,"UPDATE Player SET rank = $rangcounter WHERE ID='$updateid'");
from
mysqli_query($con,"UPDATE Player SET 'rank' = $rangcounter WHERE ID='$updateid'");
From your explanation I understood that you could have
userId | rank
1 1
2 2
3 5
4 6
5 3
6 4
and after deleting user with with id=3 you want to have:
userId | rank
1 1
2 2
4 5
5 3
6 4
If the above is correct then all what you need is to excute after deleting the user
UPDATE Player SET rank = rank-1 WHERE rank > $theDeletedsRank
should not use single quotation '' for column names. Also always use php variables outside of query string like below.
Please try this.
mysqli_query($con,"UPDATE Player SET rank=".$rangcounter." WHERE ID=".$updateid."");
Hope this works fine.
This question is bit complex atleast for me. Well, I am working on a project and need some bit more help..
Actually i have a module , where when 1 user login he get limited data from 1 table and he update its records. That is done !
second thing, the issue : i have 5 user who will login and will work on data.
but no user should get same data, like we have 1000 records.
Then when 1st user login: he get 10 records from 1 - 10.
2nd user login : he get next 10 ; 11- 20.
same so on..
and when next day they login ; they get records from 51.
because 5 user last day worked on first 50 data records.
My issue is how to achieve that 2 goals ?
do i need a framework for this ?
or it can be done using simple php n sql ?
any support will be helpful for me. :)
Ok. This is just a raw answer to give you a better idea. This is how you will insert the login .
Consider having a table containing following fields,
Table Name: Temp_Table
user, assigned_rows_last_no, date_assigned
<?php
$con=mysqli_connect("example.com","hiren","abc123","my_db");
// These things can be included into a single file say config.php and including in every file so that you dont need to specify connection string everytime.
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//This query required to be included into the file, which is exactly after login.php
$sql = mysqli_query($con,"SELECT assigned_rows_last_no FROM Temp_Table ORDER BY assigned_rows_last_no DESC LIMIT 1");
// This is because I want the last row number assigned to the user.
IF ($sql == 0) // Check whether the return answer is NULL or not.
{
// If the result is empty than add new entry of the user with defined row number.
// Suppose that current username can be retrieved from SESSION and stored into a variable.
$insertquery = mysqli_query($con, "INSERT INTO Temp_Table Values ('" . $username . $"', 10, CURDATE()");
mysqli_close($con);
}
else
{
// Select the last entry of row and add 10 to it. Ex. User2 has been assigned to 11-20, table contains 20 in the row of user2, now user3 comes, this query will select the row_no, add 10 and insert again into the table (i.e. value 30 which means 21-30.)
settype($sql, "int");
$sql = $sql + 10;
$insertquery = mysqli_query($con, "INSERT INTO Temp_Table Values ('" . $username . $"', '" . $sql . "', CURDATE()");
mysqli_close($con);
}
mysqli_close($con);
?>
The field Date will help you to recognize the entries of today, so that you can set your logic for "There should be no duplicate entries for the same user on same day"
Now, Make you own page, which check the above mentioned things, and assign the rows to the users.
Note: This code will only be able to clear out the logic for you, I am not sure whether it will work in your code without any changes.
You don't need a extra framework. Simply done with php 'n' sql!
Why you don't save the last edited lines (linenumbers) in a extra SQL-Table? Maybe with the username / userid.