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.
Related
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'";
}
?>
I have a form that shows some images and other data from a mysql table. Using radio buttons the 'galley' field for the selected image gets changed to 3. I have this working ok, however there should only ever be one value of 3 in the table. How could i change the code below to also change any 3 already in the table to a 1 value?
// if featured is checked, then set gallery field to 3
if(isset($_POST['featured'])){
$chk = (array) $_POST['featured'];
$p = implode(',',array_keys($chk));
$t = mysqli_query($link, "SELECT * FROM gallery WHERE id IN ($p)");
if ($t){
$q = mysqli_query($link, "UPDATE gallery SET gallery=3 WHERE id IN ($p)");
header('Location: galleryadmin.php'); exit();
}
else{
echo '<script type="text/javascript"> alert("Dog Has Not Been Featured, Try Again
Or Contact Site Developer") </script>';
}
}
Can anyone help?
UDPATE yourtable
SET gallery = IF(id = $p, 3, 1)
for records where id = $p, the if returns 3. For any other record, it returns 1, and those 1/3 values get assigned to the gallery field.
This is somewhat inefficient, if you're on a very large table, where it'd be re-writing all but one record to basically have the same value the record had before. Performance-wise, you might be better off using a transaction and two queries:
start transaction;
update yourtable set gallery=1 where gallery=3;
update yourtable set gallery=3 where id=$p;
commit;
which should theoretically only change two records: the "old" gallery-3, and the new one that's becoming gallery-3.
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.
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.
How can I make a limit of showing the results? I need to limit it for 100 views.
In DB I have:
ID|NAME|PAGE|COUNT|DATE
In count I want to count untill 100 and then stop showing that ID. I could do it with count < 100. And then update the specific ID. I could get records with less than 100 views, but I couldn't manage to update count on the specific ID.
Row is showed with:
php code:
foreach($bannerGroups[0] as $ban) {
echo '<li class="right1">'.$ban->html().'</li>';
}
But I just don't know where to put the update in there. I tried, but all I got was to update only one ID. But it shows 4 on one page and randomizes them on refresh. So I don't know what to do.
Also I would like to say I am only learning php. Sorry for all the mess.
Code at http://pastebin.com/A9hJTPLE
If I understand correctly, you want to show all banners that have been previously-displayed less than 100 times?
If that's right, you can just add that to your WHERE clause:
$bannerResult = mysql_query("SELECT * FROM table WHERE page='cat' WHERE `COUNT` < 100");
To update them all, you can either run a query while displaying each individual banner, or "record" the id of each and run a single query at the end, like:
$ids = array();
foreach($bannerGroups[0] as $ban) {
$ids[] = $ban['ID']; // record the ID; don't know how Banner
// class works, assuming uses indexes; maybe ID() method?
echo '<li class="right1">'.$ban->html().'</li>';
}
...
mysql_query('UPDATE table SET `COUNT` = `COUNT` + 1 WHERE ID IN (' . join(',', $ids) . ')');
UPDATE:
Based off of a comment, your Banner class doesn't have a method to retrieve the individual banner's ID. In this case, you can record the ID values when you're building your banners array:
$ids = array();
while($row=mysql_fetch_assoc($bannerResult)) {
$banners[] = new Banner($row);
$ids[] = $row['ID']; // record the ID
}
// update the `count` on each record:
mysql_query('UPDATE table SET `COUNT` = `COUNT` + 1 WHERE ID IN (' . join(',', $ids) . ')');
sorry, but I got your question wrong...
first you have to insert a new sql-column like "viewcount" to the db...
on every read, you have to increment the value in viewcount...
for that behaviour (because, mysql does not allow sub-selects on update-clause on the same table), you have to fetch the results from db, as you do that, and pass all the primary-keys of the records to an array...
after the view-logic you have to fire up a query like:
UPDATE foo SET viewcount = viewcount + 1 WHERE id IN (1,2,3,4,5,6...,100);
where the IN-clause can be easily generated using your primary-keys-array with "implode(',', $arr);"
hope this helps.
$bannerResult = mysql_query("SELECT * FROM table WHERE page='cat' AND `count`<100");
#newfurniturey figured it out. in each foreach($banneruGroups added: $ids = $ban->getValue('id'); and then mysql_query("UPDATE dataa SET COUNT = COUNT + 1 WHERE id = '$ids'"); but is there any way to update them by adding query only once? And if the id is showed already 100 times i get Warning: Invalid argument supplied for foreach() in. Any idea how to fix it? I have 4 ids in DB . If one of them already have 100 views (count) then i get error!
Try to limit your data source for 100 items.
It's like OFFSET x LIMIT 100 in MySQL/PostgreSQL query or TOP 100 in MSSQL.