Suppose i have a database that store report from employees which first column is reportID(auto increment), staffID,name,department and so on.
Everytime i submit i report from my php page it will display increment number (reportID) in my php page. So lets say i got 3 report ID stored in the table, i want to delete three record, and then add 1 new record to the table, but now the reportID display as 4 because the past three reportID are 1,2,3, so how do i reset the new record to 1 instead of 4? is there a code to reset it?
This is my deletereport.php
<?php
include('adminconfig.php');
include('config.php');
$reportID = mysql_real_escape_string($_GET['id']);
$sql="DELETE FROM `report` WHERE `reportID`='$reportID'";
$result=mysql_query($sql);
if(!$result){
die('invalid query:'.mysql_error());
}
else
?>
<p style="font-family:arial;color:#0066CC;font-size:30px;">One row deleted...</p>
<?php
header('Refresh:3; url=viewreportdb.php');
die;
?>
You have to truncate the table to reset auto incremented values
or just
ALTER TABLE yourtable AUTO_INCREMENT = 1
similar discussion here
Auto Increment after delete in MySQL
Probably don't want to reset and just use auto-increment.
query following from PHP:
ALTER TABLE tablename AUTO_INCREMENT = 1
Related
Is there a way to auto-increment in MYSQL after deleting a row from the database?
For example:
There is a table with 3 columns: StudentID, Student Name, and Contact details. Here StudentID will be the primary key which will keep incrementing after adding values in each column.
The PHP code will look as follows:
<?php
require_once "Delete_Form.php";
if ($_GET || id['id']) {
$id = mysqli_real_escape_string($db, $_GET['id']);
} else {
echo 'Value was not brought over';
}
echo $id;
$result = mysqli_query($db,"SELECT StudentID, StudentName, Contact FROM student WHERE
StudentID='$id'");
$row = mysqli_fetch_row($result);
$sql= "DELETE FROM `student` WHERE `student`.`studentID` = $id";
echo "<pre>\n$sql\n</pre>\n";
mysqli_query($db,$sql);
echo 'Success -Continue...';
return;
Once we delete an entry from the database the Auto-Incrementation of StudentID will mess up i.e if the last entry had a StudentID of 12 and then we delete the same then the next row we enter will have StudentID of 13.
We can always do ALTER TABLE `student` AUTO_INCREMENT = 1 which will reset it but that will solve the problem temporarily only.
Is there a way to add a PHP statement in the above code to reset auto increment whenever we delete a row?
Do it never.
Primary key in a table identifies the row uniquely during the whole table lifetime. Pay attention - TABLE lifetime, not ROW lifetime. The fact that the row was deleted changes nothing - the value identifies this deleted row nevertheless.
If you need rows enumeration without the gaps then create special column for this purposes or enumerate in a query.
PS. By the way, synthetic AI PK must be hidden for the user at all - this column destination is row identifying and foreign keys subsystem work. It must not have any additional meaning.
I am trying to generate a temporary ID for a student registration process, for applicants who do not have a specified identity document. However, there were instances when the some applicants used arbitrary ID numbers which are in the series we have selected for official temporary ID number generation.
When I create a temporary ID (via the c_nic table), I need to check whether that ID is already used by an applicant (in the a_student table) and if yes, skip that number to the next number in c_nic, so on and forth. I am using the auto_increment of the temporary ID table (c_nic)
e.g. When a student comes in for registration and he doesn't have an ID number, we will generate a temporary ID for him. This will be the auto_increment in the c_nic table. Say, 11001111. Before releasing this ID for the student's use, I need to check whether this has been used by another student by mistake. If 11001111 is used by another student for his registration, I need to give the current student the next available ID, which may be 11001112 or if that is also used 11001113 and so on. When the new student is given the new temporary ID, I need to adjust the auto_inc value in the c_nic table, so that the second new student gets the next available ID number.
I tried with the following code, but the auto_increment does not increase even if there is a records already exists in the a_students table
$refid = mysqli_query($conn, "SELECT `AUTO_INCREMENT` AS id FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '".DB_NAME."' AND TABLE_NAME = 'c_nic'");
$refnum = mysqli_fetch_assoc($refid);
$ref = $refnum["id"];
$refnew = $refnum["id"]+1;
$chkduplicate = mysqli_query($conn, "SELECT nic FROM a_students WHERE nic='$ref'");
do {
$chkduplicate = mysqli_query($conn, "ALTER TABLE c_nic AUTO_INCREMENT = '$refnew'");
$refnew = $refnum["id"]+1;
echo '<br/>Ref: '.$ref;
echo '<br/>Ref New: '.$refnew;
}
while (mysqli_affected_rows($conn) >0 );
I suggest you to use table as auto increment & primary key for unique student id
like below
ALTER TABLE a_students
ADD PRIMARY KEY (nic);
ALTER TABLE a_students AUTO_INCREMENT = 1;
<?php
include('connection.php');
/* code for id goes here */
$q2= "select MAX(id) from usertable";
echo mysqli_query($sql,$q2);
$name=$_POST['name'];
$username=$_POST['usrname'];
$password=$_POST['psw'];
$dob=$_POST['date'];
$query="insert into usertable(name, username, password, dateofbirth) values('$name', '$username','$password','$dob')";
if(mysqli_query($sql,$query))
{
echo "Registered successfully";
}
?>
This is my insert command to register a user in my database. However the database contains a column named id which is the primary key. How do I fetch the id before executing the insert query so that it fetches the last id and increments it by 1 and inserts it in the db along with the other data. The id is numeric and I want the program to perform the operation itself rather than the user entering the data of the id. Please help.
You need to set your id field to auto incement and your database will do it automatically:
ALTER TABLE usertable MODIFY COLUMN id INT auto_increment;
You need to write a query
SELECT MAX(id) FROM usertable
and get the result from that and then increment that value by 1 and then set that value in id field.
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'
);");
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