Mysql after deleting record decrement other ID's - php

I have the database where i save my records. The records was saved as
ID, name
example
Nick
Name
Username
Now when i delete the record with id 2. in my database it remains as
1. Nick
3. Username
I want that when i delete one record from database other id's automatic decrement for one value so i get.
1. Nick
2. Username
Do you understand my question. Sry for bad english
Button delete code
if(isset($_POST['tipkaobrisi'])) // pritisnuta tipka obrisi
{
$obrisankorisnik = $_POST['obrisi'];
if ( $obrisankorisnik == '' )echo "<div align='center'>Unesite korisnika kojeg zelite obrisati!</div>";
else
{
mysql_query("DELETE FROM Korisnici WHERE Korisnik ='$obrisankorisnik'");
echo "<div align='center'>Korisnik obrisan<br><br></div>";
}
}

That is not the intention of most ID columns. However, you can mimick this functionality by modifying the statement you use to access those records.
E.g. rather than using the ID value, use the following
select #rownum:=#rownum+1 as ID, name from users, (SELECT #rownum:=0) r order by id;
It will give each record returned a number, with no gaps. Depending on what you want this for, that may be enough. If you would like to treat this new ID value as the ID value, create a view and access your elements based on that, like so:
CREATE VIEW users_view as select #rownum:=#rownum+1 as ID, name from users, (SELECT #rownum:=0) r order by id;
at which point you can SELECT * FROM users_view WHERE ID = $id and have it work as usual. So long as you never insert a new record that is not auto incremented, this scheme should work.
Keep in mind that deleting anybody changes a bunch of IDs, so it's not recommended.

After listening other programer's advice's. I decide that i don't want to edit my ID's.
Thanks to all for participating.

Related

Adding database entries together

I am making a site which allows admins to basically add points for a user.
At this point in time, I have a table, where id_child is unique, and id_points changes. So a constant stream of id_points can come in, however, it will only show the latest id_points, not the total.
I am wondering how I could go about creating a PHP script that could add all of those together.
From the image, the idea is that I want all id_points values added together to give a total, and this is for the same id_child
Use SQL sum() funciton:
select sum(id_points) from table `table_name` where `id_child` = 1
Hope i understood right.
First if you want to show only the latest points added you have to create another table #__points where you will keep every new change of points.
You need 3 columns id as PRIMARY and AUTO_INCRENMENT , pts and user_id . user_id will be FK to id_child.
So when you want to add a new record :
INSERT INTO `#__points` (pts,user_id) VALUES ("$pts",$id)
When you want to select last inserted value for each admin :
SELECT * from `#__points` where user_id=$id ORDER BY id ASC LIMIT 1

Mysql trigger from one table to another

So, I have a table A that each time a user sends an image, a record is created storing the time it was uploaded, the username of the user and the image number out of all the images uploaded over time.
I need to make a second table B that will store the amount of images uploaded per user and the user name. I need this table B to be updated when a new entry is generated in A.
I found that a trigger function can be created, nevertheless I'm having a rough time finding an example that will suit my needs.
Does anyone know a way of doin what I want?
Just update b table with a select count of total inserted records on a from current user NEW.userid (userid is your column name or whatever name you have there, and NEW is a fixed mySql reference for the current values to be inserted):
CREATE TRIGGER img_sum AFTER INSERT ON a
FOR EACH ROW SET b.total = (SELECT COUNT(*) FROM a WHERE a.userid=NEW.userid)
WHERE b.userid = NEW.userid;
From what you have described i don't think you need a second table. You can just count the number of time a user name has occurred, and you will get the number of images that user has uploaded.
You can get the count doing something like that
SELECT COUNT(DISTINCT username) FROM table_name;
If you still need to create 2 tables, you might want to take a look at procedures and how they work.
Let's say we have 3 tables for this case:
- users(id, username, email ....),
- user_images(id, userId, image_num, date_uploaded)
- user_images_count(id, user_name, images_count)
The user_images_count is initially empty. We have to fill it up by such query:
INSERT into user_images_count(user_name, images_count)
SELECT (select username from users where ui.userId = id) as username, count(userId) as counter FROM `user_images` ui group by ui.userId;
Then, we must immediately create the trigger that will process every INSERT operation into user_images table.
CREATE TRIGGER `count_user_images` AFTER INSERT ON `user_images`
FOR EACH ROW begin
declare u_name tinytext default "";
set u_name = (select username from users where id = NEW.userId limit 1);
if(u_name != "") then
update user_images_count set images_count = images_count + 1 where user_name = u_name;
end if;
end
This two queries (user_images_count fulfillment and trigger creation must be performed in one transaction, one by one).
I've created similar triggers on my local databases. They work pretty good. )))

How do I delete a row if there are 4 or more rows named after the username

My professor wants us to create a web-based comment system wherein a user can send up to 3 comments, if the user decides to create another one when he already has 3 comments named after him on the database, the program should delete the oldest one and save the new one.
What I thought about was to fetch the rows named after the user and if it is greater or equal to 4, I should delete the row where username = session user and insert the new record. Although this was just in theory, is this the best way to go about this? Do you guys have any other suggestions? How exactly do I pick the rows to remove? Do I base it off the highest comment_id?
Read: Leave only first 50 records in SQL database and delete the rest
So basically do this:
Create an Auto Increment Id with the comments.
Then:
DELETE FROM comments
WHERE
id NOT IN (
SELECT * FROM (
SELECT id
FROM comments
ORDER BY date
desc LIMIT 3) s
)
Do not delete the rows in the database, just do a limit 0,4 on your select query
with a order by on a create date

How to remove duplicates correct?

I have a MySQL chart table like this : PRIMARY KEY(ID), Name, Value, Date
I need to remove duplicates if "Name AND Value AND Date" are the same as existing row.
I have beneath a solution i found while ago and which worked (not 100%), but I don't understand the command in it's total because I'm only into BASIC MySQL... Can somebody explain me a little further...
definitely what is the x at the end ???
$delDups = "delete from chart where id not in (select * from (select min(id) from chart n group by value) x)";
mysql_query($delDups);
It appears to me that you could do it simpler, like this:
$delDups = "delete from chart where id not in (select min(id) from chart n group by value)";
In the subquery you are saing:
" Hey, take all the values and find the minimun id for the group of values"
So, imagine the result of the subquery as a list, like "(12, 13, 200)".. the NOT IN operator will take that list and use it to filter the result of the upper query and say "Give me all the results, less the ones where id is in this list"
I'm not sure if I explained it as expected...
You could add an unique key for all 3 columns:
ALTER IGNORE TABLE my_table
ADD CONSTRAINT uc_unic UNIQUE (Name, Value, Date)
As to that x,mysql permit aliases,essentially name shortcuts for convenience.
What you wrote will almost work, you just want to add the name and date to the GROUP BY clause. Something like this should do.
DELETE FROM chart
WHERE id NOT IN (
SELECT MIN(id)
FROM chart
GROUP BY name, value, date)
The DELETE FROM says you want to be deleting rows from a table. The WHERE clause says which rows you actually want to delete (missing it out will remove everything). The sub-query in the brackets will look through every combination of name, value and date and give you one id back from each combination. Putting it all together, the DELETE should now drop every row whose id isn't the smallest for each group.
Hope that helps!

Check last entry before inserting into DB

Can someone give me a quick hint on how I can achieve the following:
I have a table with 3 rows: id , value1 and user.
let's say there's 1 entry in the DB with the following data:
1, test, user1
Now when I submit my form and before the next thing gets actually inserted, I want to check the value of user of the last entry in the DB and change the next entry to either user1 (if the last one is user2) or user2 (if the last one is user1)
Edit:
I think I explained it a bit stupid.
Basically I want some kind of Zebra striping for the row user if that makes any more sense :-)
It can be even easier:
SELECT user FROM table ORDER BY id DESC LIMIT 1
Assuming that id is an AI field.
EDIT: adding some PHP code:
$getLastUser = mysql_query("SELECT user FROM table ORDER BY id DESC LIMIT 1");
$LastUser = mysql_fetch_array($getLastUser);
$newUser = ($LastUser['user'] == "user1") ? "user2" : "user1";
//insert $newUser to the 'user' field.
You can proceed by executing a query like
SELECT user FROM table WHERE ID IN(SELECT MAX(ID) FROM table)
and then using that user value to determine what the next user value would be.
To avoid concurrency issues, do it all as one statement:
INSERT INTO your_table (value1, user)
VALUES ('your_value', (CASE (SELECT user FROM your_table ORDER BY id DESC LIMIT 1) WHEN 'user1' THEN 'user2' WHEN 'user2' THEN 'user1' END))
Looks like you need your Zebra striping at the output, not insert time.

Categories