Increment a column based on its id in mysql - php

Im making a drag n drop sortable list. What I am trying to do is increment a column in MySql based on its id value automatically when new records are entered. ie:
if i have a row with an id = 3, and it is the first record enetered
for that id, then its recordid = 1.
if i have a row with an id = 14, and it is the first record enetered
for that id, then its recordid = 1.
if i have a row with an id = 3, and it is the second record enetered
for that id, then its recordid = 2.
So i want it to autoincrement recordid based on its id value. not the whole table value. Does that make sence? what code would i need in php to find the highest value recordid pertaining to the id and then increment it by 1 when a new record is entered? Thanks in advance.

Something like this?
INSERT INTO `table` (`id`, `recordid`) VALUES
(
$id,
(SELECT MAX(`recordid`) + 1 AS `rid` FROM `table` WHERE `id` = $id)
);
You could probably optimize it way further though.

Related

Update data in mysql column field without removing previous value

I am trying to update "new" column value with new value but problem is my query remove previous data while inserting new value
What is want: here is example table structure,
Table name = agg_lvl primary key set = uid
uid | new
--------|--------
1 | 100
2 | 300
You can see "new" has 100 points, for example I send 100 new points to user 1, so new column value should be 100 + 100 = 200, right now with this code
$query4 = mysql_query("INSERT INTO agg_lvl (uid, new) VALUES ('$uid','$new')
ON DUPLICATE KEY UPDATE uid='$uid',new='$new'");
Not sure what
new = '$new'
I have tried both ways but no success = >
new = 'new + $new' or new = new + '$new'
You should make changes in your query
Make num = nun+$num to add new value to old one
Remove quotes arount $new because it is a number but not a string
Remove uid from set list because insert already point to that record
And your query should look so:
$query4 = mysql_query("INSERT INTO agg_lvl (uid, new) VALUES ('$uid','$new')
ON DUPLICATE KEY UPDATE new=new+$new");
Okay first i will answer with the proper way to do the same, In this case i am assuming that UID is unique, so you make a new table scorecard with UID as foreign key. Now rather than update, you just insert stuff to table like if UID 1 gains 10 and 20 points, there are two entries. onw with 10 and one with 20. Now to get his current points, you add all points where UID=1 .
Now in your implementation the correct query would be
UPDATE userData SET points = points + x WHERE UID = $uid
where x is the new points gained and points is the name of column
$query4 = mysql_query("INSERT INTO agg_lvl (uid, new) VALUES ('$uid','$new')
ON DUPLICATE KEY UPDATE uid='$uid',new=new+$new");
worked for me with help of #splash58

putting values in between the ascending database column

Following is my database in mysql:
Id Username Password
1 admin admin
2 jay jay1
3 suman xyza
4 chintan abcde
This is my code in php:
$fetchid = mysql_query(" SELECT MAX(Id) As max From user;");
$row = mysql_fetch_array($fetchid);
$largest = $row['max'];
$largest++;
$user= $_POST['username'];
$pass= $_POST['password'];
$result = mysql_query(" INSERT INTO `proshell`.`user` (
`Id` ,
`Username` ,
`Password`
)"."
VALUES (
'".$largest."', '".$user."', '".$pass."'
);");
Problem:
Now if I delete row with Id=1 and then re-enter the data then it should use ID=1 then Again I reinsert the data it use ID=5
It works like this:
if I delete row with Id=1 and then re-enter the data the Id it gets is 5 but then 1 is free so,
What should I write to perform that task.
First, if you set your Id column to AUTO_INCREMENT you don't need the following part in your code at all:
$fetchid = mysql_query(" SELECT MAX(Id) As max From user;");
$row = mysql_fetch_array($fetchid);
$largest = $row['max'];
$largest++;
Because AUTO_INCREMENT will automatic add new value to your ID colume.
But if you don't set it to AUTO_INCREMENT, the above code will grab the MAXIMUM ID value (in this case, 4).
When you re-enter your data again after you delete the row 1, the MAXIMUM ID still 4, so your new ID value will be 5 (from $largest++;).
.....
If you really need to use consecutive ids as you PK, you need to re-write you code but I suggest you to use UUID for you ID column instead.
You can easily generate UUID by using uuid().
How about the UUID performance? Refer to Dancrumb's answer about this:
A UUID is a Universally Unique ID. It's the universally part that you should be considering here.
Do you really need the IDs to be universally unique? If so, then UUIDs
may be your only choice.
I would strongly suggest that if you do use UUIDs, you store them as a
number and not as a string. If you have 50M+ records, then the saving
in storage space will improve your performance (although I couldn't
say by how much).
If your IDs do not need to be universally unique, then I don't think
that you can do much better then just using auto_increment, which
guarantees that IDs will be unique within a table (since the value
will increment each time)
see. UUID performance in MySQL?
EDIT: I don't suggest you run query on the whole table just to find the MAX ID value before inserting new value everytime, because it will give you a performance penalty (Imagine that if you have million rows and must query on them everytime just to insert a new row, how much workload causes to your server).
It is better to do the INSERT just as INSERT, no more than that.
EDIT2:
If you really want to use consecutive ids, then how about this solution?
Create new TABLE just for store the ids for insert (new ids and the ids that you deleted).
For example:
CREATE TABLE cons_ids (
ids INT PRIMARY KEY,
is_marker TINYINT DEFAULT 0
);
then initial ids with values from 1-100 and set marker to be '1' on some position, e.g. 80th of whole table. This 'marker' uses to fill your ids when it's nearly to empty.
When you need to INSERT new Id to your first table, use:
$result = mysql_query("SELECT ids, marker FROM cons_ids ORDER BY ids ASC LIMIT 1;");
$row = mysql_fetch_row($result);
and use $row[0] for the following code:
INSERT INTO yourtable (Id, Username, Password)
VALUES ($row[0], $username, $password);
DELETE FROM cons_ids
WHERE ids = $row[0];
This code will automatically insert the lowest number in cons_ids as your Id and remove it from the cons_ids table. (so next time you do insert, it will be the next lowest number)
Then following with this code:
if ($row[1] == 1) {
//add new 100 ids start from the highest ids number in cons_ids table
//and set new marker to 80th position again
}
Now each time you delete a row from your first table, you just add the Id from the row that you deleted to cons_ids, and when you do INSERT again, it will use the Id number that you just deleted.
For example: your current ids in cons_ids is 46-150 and you delete row with Id = 14 from first table, this 14 will add to your cons_ids and the value will become 14, and 46-150. So next time you do INSERT to your first table, your Id will be 14!!.
Hope my little trick will help you solve your problem :)
P.S. This is just an example, you can modify it to improve its performance.
First of all, as I understand, you are selecting highest column ID which should be always the last one (since you set auto-increment on ID column).
But what are you trying to do is actually filling up holes after delete query, right?
If you are really looking for such approach, try to bypass delete operation by making new boolean column where you flag record if it is active or not (true/false).
SQL table change:
Id Username Password Active
1 admin admin false
2 jay jay1 true
3 suman xyza false
4 chintan abcde true
PHP request:
$fetchid = mysql_query(" SELECT MIN(Id) As min FROM user WHERE active = false;");
$result = mysql_query(" INSERT INTO `proshell`.`user` (
`Id` ,
`Username` ,
`Password`
`Active`
)"."
VALUES (
'".$largest."', '".$user."', '".$pass."', 'true'
);");

Set UNIQUE priorities ON DUPLICATE KEY

I have the following table
id year name activation
1 2013 TEST 1
id A_I
year, name UNIQUE
name, activation UNIQUE
I use this query to INSERT/UPDATE data:
INSERT INTO LISTE_DATI
(year, name, activation)
VALUES
('$varray[1]', '$varray[2]', '$varray[3]')
ON DUPLICATE KEY UPDATE
year= '$yr',
name= '$na',
activation= '$act'
If I send this data to the table:
$yr = 2014
$na = TEST
$act = 0
the query INSERT data in the table. This is ok for me!
If I send this data to the table:
$yr = 2015
$na = TEST
$act = 1
the query UPDATES the first row (2013/TEST/1) in the table.
In this case I'd like to have an INSERT too.
How can I adjust it?
You are telling your INSERT query, that when it finds a duplicate (UNIQUE) key, to instead update that row.
You are inserting (2012, 'TEST', 1). This is a duplicate key; the name, activation key, your 2nd UNIQUE key! You already have a row with 'TEST', 1; the row with id=1.
The INSERT query updates that row, since it's a duplicate key.
You need to modify the keys on your table so that it reflects the data you want in it. What do you want the INSERT query to consider a duplicate? Create your UNIQUE keys based on that.

Insert multiple rows with same unique ID

I am inserting multiple rows using one query and, obviously, the ID column auto increments each row. I want to create another ID column and have the ID remain the same for all rows inserted during the query. So if I insert 10 rows during one query, I want all 10 rows to have the id "1". How can this be done? Thanks for any help
If I understood your question correctly, you want to supply an ID for the specific group of INSERT statements.
Assumming you have this schema
CREATE TABLE TableName
(
RecordID INT AUTO_INCREMENT PRIMARY KEY,
OtherColumn VARCHAR(25) NOT NULL,
GroupID INT NOT NULL
)
You can have two statements for this:
1.) Getting the last GroupID and increment it by 1.
SELECT COALESCE(MAX(GroupID), 0) + 1 AS newGroupID FROM TableName
2.) once you have executed it, store the value in a variable. Use this variable for all the insert statement,
$groupID = row['newGroupID'];
$insert1 = "INSERT INTO TableName(OtherColumn, GroupID) VALUES ('a', $groupID)";
$insert2 = "INSERT INTO TableName(OtherColumn, GroupID) VALUES ('b', $groupID)";
$insert3 = "INSERT INTO TableName(OtherColumn, GroupID) VALUES ('c', $groupID)";
UPDATE 1
SQLFiddle Demo

How to insert a custom inscription ID of a user in mysqli?

I'm working on a school manager script.
I don't know how to insert a custom unique id of subscription...
I just use this function to show it's unique subscription's id when showing his/her full informations from the database:
$year = date('Y');
$ID = substr($student->dateNaissance,8,10).$student->id_etudiant."/".$year;
The function is combined of 3 things:
The 2 last digits of the year of birth (example: 01/01/1981.. i take only this -->81 using the substr function)
The row id from the table on the database (ex: 50).
And the year of subcription(example: 2013)
all that gives me , for example, as result 8150/2013
what i want here is when inserting the student data into the database , i want this unique ID to be inserted as well..
The problem here is i don't know how to get the last id of a row !
Yeah, I tried to insert the student data and then update the id_subscription using this:
if(isset(....){
......
$mysqli->query("INSERT INTO table (a,b,c, ...etc) VALUES('','',''..etc)");
$year = date('Y');
$mysqli_query("SELECT * FROM table_name");
$studentID = $mysqli_insert_id();
$ID = substr($student->dateNaissance,8,10).$ID."/".$year;
$mysqli->query("UPDATE table_name SET id_subscription = $ID");
}
But its not working :\
By the way: in my table Im using an auto_increment id + the subscription_id in which i want to insert the customized id I showed above.
Assuming that row id is an auto_increment field, then you'd have to do it in two stages:
start transaction
insert everything into the DB EXCEPT your id field
use last_insert_id() to get the mysql-generated ID field
build your own id field
update the record with this new id
commit the transaction.
On Database Structure:
1. you can use auto-incremented primary key in your table and store the data(student_id) as a seperate column(recommended).
On getting 'the last id of a row':
1. Use mysql_insert_id() .. check this out

Categories