I want to get last id in mysql and php [duplicate] - php

This question already has answers here:
Get most recent row for given ID
(7 answers)
Closed 5 days ago.
hi i want to get last id from my table then i will put it in registration form with +1 mean's +1 id will be automatically generated when any form inserted i'm doing this because i have 4 user's i want that id no of registration forms starts from 1 for every user
SELECT *
FROM registration
WHERE id=(SELECT MAX(id) FROM registration);
i use this code but i'm unable to add AND condition i need something like
SELECT *
FROM registration
WHERE id=(SELECT MAX(id) FROM registration)
AND project_name='test2';
this mean i want to add AND condition where it will check this project_name last id

Riggsfolly already warned you about generating your own IDs.
It is MUCH safer to let the database generate UNIQUE ID's.
(Almost) Every table I create gets a primary key that has some form of SERIAL in it.
For example: For Postgres I use SERIAL:
CREATE TABLE registration (
registrationid SERIAL PRIMARY KEY,
project_name VARCHAR(100),
whatever VARCHAR(1000)
)
You seem to use MYSQL: Look up AUTO_INCREMENT.
Now, if you insert into that table, you do it without the registrationid:
INSERT INTO registration (project_name , whatever ) VALUES ('test2', 'hi there');
If this is the first insert in the table registrationid will automagically become 1.
Next insert is will be 2. etc etc.
Now suppose you did this 1000 times, you next one will then be 1001.
When you delete a few, that doesn't matter, the next will be 1002.
Now: If you want the query for the highest registrationid AND some project_name, do it like you did, but make sure you get the MAX() of the ones that have your desired project_name:
SELECT *
FROM registration
WHERE registrationid= (SELECT MAX(registrationid) FROM registration WHERE (project_name='test2') ) ;
2 last observations:
Follow Riggsfolly's advice and do not generate your own uniqueness, but let the database do this using appropriate syntax when defining your table (SERIAL for Postgres, AUTO_INCREMENT for MySQL, etc).
In my example the inserts are naive. It is better to use PDO for databinding when working with strings to avoid SQL-injection.

Related

automatically insert random value in column

I want to generate random number of 6 digit in mysql.
For example,
I have a table named as DATA and columns are job_name and job_id.
So, when user insert value in job_name and the value of job_id which would be random and unique number which will be stored in database automatically.
I have been searched for this but can not get anything out of it. So, Please specify your answer in brief.
Give job_id the primary key and use Auto Increment in your database.
This way you just have to insert job_name and it will auto_increment the name by itself. Auto Increment
P.S. this is not random, but there shouldn't really be a reason for it to be random? otherwise you'd have to make a script that keeps making random numbers and comparing them to the database until one doesn't exist yet.
If you really want it to be random check this post
I really suggest that you don't do this, there might also be a day where you run out of ids and it will get stuck in an endless loop if you limit it to 6 characters.
try this query
INSERT INTO `DATA`(`job_id`, `job_name`) VALUES (ROUND((RAND() * (999999-100000))+100000),'php developer')
Use 2 fields in your table. One is your AUTO_INCREMENT job_id and another new field: job_unique_id.
You can insert unique random values in that column using mysql UUID function. From your tags it seems like you're using codeigniter. In codeigniter use the following code for generating unique tokens:
$data = array(
'name' => 'full name'
);
$this->db->set('job_unique_id', 'UUID()', FALSE);
$this->db->insert('my_table',$data);
Check this link for more info: http://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_uuid

How do i set the increment value of autoincrement in mysql

I am trying to develop a system to assign room numbers to tenants of a hostel upon registration, using the auto increment feature of sql.
However, it automatically increases by one after every entry. Because the hostel accommodates four people in one room, I want to change this to 4, so that after every 4 entries I get only one id/room number.
How do I go about this? I am using php and sql. If the autoincrement feature is not possible can you please suggest another way to achieve this? Thanks.
You would need:
http://dev.mysql.com/doc/refman/5.1/en/replication-options-master.html#sysvar_auto_increment_increment
It works like this:
mysql> SET ##auto_increment_increment=4;
So when you insert 4 rows, the auto increment column will be:
4,8,12,16
as best of my knowledge you cannot change the steps of auto-increment field. I suggest add another field and write a trigger to update its value based on auto-increment field (auto-increment/4).
I don't think this is possible with autoincrement..
Maybe you can do something like this:
//Pseudo code
//First you get the count of the highest id, to see how many users are in the last room.
SELECT COUNT(*) FROM table WHERE id=(SELECT id FROM table ORDER BY id DESC LIMIT 1)
//If the result of the last query is >= 4 then insert the next customer with id +1
Don't use auto_increment for this - it can't handle a situation where multiple records will share the same number and although you can reset it manually (see below) it's also not designed for a situation where numbers may get reused in a random order.
You could just have a room_number field with one of the mysql integer types (e.g. tinyint, smallint, mediumint…) or you could separate your database into two tables, one for people (each of whom have an id) and a second to map those ids to rooms.
However you do it, you'd then write a select query to check which room numbers are available before you add the person's details to the database.
You may need to read up on relational databases if that doesn't sound very clear.
If you do need to reset the auto_increment (sometimes it's nice to do it if you've filled a database with test data which you're about to wipe, and you want the real "production" data to begin at 1) you can use:
ALTER TABLE [tablename] AUTO_INCREMENT = 1
https://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Find the size of an SQL column with PHP?

I'm trying to build a very simple login system for my site (just for practice for a project i'm working on). The way I've decided to implement it is use a table with fields for ID, Name, Password, and username and search for the entered information in the existing table.
For registration, it simply injects the information supplied into the table, and I would like to assign a customer ID number. My idea for assigning an ID number is to simply find the size of the ID column (which will contain the ID's 1,2,3..etc up to the end) and assign the new registration to the length +1. For this purpose i'll need a way to get the size of the column, but I'm just learning php and sql so i'm not sure what the syntax would be.
TLDR; is there a funtion in sql that I can use in php to get the length of a particular column? (i.e the number of entries stored in that column?)
Set the ID column to Primary and Auto increment.
you don't include that in your query it is created on its own.
You'd probably be better off just using an IDENTITY or AUTO_INCREMENT column. The problem with checking for the "size of the column" (by which I assume you mean the count of rows in that column) is that you could end up inserting duplicate IDs, for example:
ID | ...
---------
1
2
4
So if you did a SELECT COUNT(ID)+1 FROM MyTable, it would return 4, and you have an ID collision.
You could do something like SELECT MAX(ID)+1 FROM MyTable, but even then there could be concurrency problems (process A and process B both try to run that query at the same time, before either has a chance to insert the new ID of 5). You're really best off just letting your RDBMS take care of it..

Add +1 to last entry with PHP/MySQL (auto-increment) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to fill in the “holes” in auto-incremenet fields?
We are currently using auto-increment on a table where entries come and go constantly. The problem with this, is that eventually the auto-increment id becomes huge, as that is how auto-increment works.
We would like to have it always add +1 to the last entry.
For example:
We have 4 entries and id 4 is deleted. Next added entry should get id 4, and not 5.
I am not sure if this has been asked before. But after searching I was only able to find solutions on how to get the next auto-increment number, which is not what I am looking for at all.
YOU SHOULD NOT DO THAT because auto_increment is designed this way for good reasons (like if you have a backup and you want to restore it when it contains old deleted id that has been rewrote, how do you do ?)
But to answer your question:
You have to use
ALTER TABLE `table` AUTO_INCREMENT = MAX(id)+1;
After a delete, you can make a trigger
If you really want to do that (I personally encourage you to use auto-increment), you need to perform a transaction in order to get the last ID and insert the new row setting its ID incrementing it according to the other one.
It's not a good idea to do this, the ID should always stay unique, no matter if the record exists or is deleted.
However if you really want to do it, you can to it with something like
select max(id) + 1 of bla;
But you need the right transaction level for it because if you don't you have a possibility of duplicated ids.
You can choose maximum id value and just increment it.
SELECT MAX(`id`)+1 as `new id` FROM `table`;
If you have 5 entries and 3rd gets deleted, this will still get you 6 as next id.

How can I get a number from 1 that is unused in database

Hi my qouestion is how to get the first number that is not used in specific database row. The number must be betwen 1 and 9999 and must be compared with all numbers in that specific database row, so if data in my database row starts with 5, i wont to be able to get the first number that is not used ...in this case the number 1. then when I create data with number 1.. the next number I need to get is 2 and...I'm using that to create profiles, and that number is the profile number, and ewery new profile must have the first unused number in data base. How to do that. I don't know where to start. So if someone can put me on the right path for solution of this problem? Thanks.
the edit
But, I dont need the auto increment i need to user to be able choosing this number on his own, first, this first number must bee suggested to the user by placeing it in the text form. And if the user select the number that is alredy in the database my program whil let the user know that he is trying to select the number that is allredy exist. So if you understand me ...I know the basics of mysql. The problem comes when the user deletes one profil then the deleted number can't be used eny more. For that i need the functio first free unused number.
New edit
I'l try to clear up some details...Frst this is the program for human resources and the user creates the dosies of workers... when user is creating the new dosie hee needs to select the dosie number for this worker, now I need to sugest to user the first unused number for the new dosie... the dosie number is not the dosie 'id'. Dosie number must be selected manualy by user or he can let the first free number to given to the new dosie... I think this whill clear some things
You are probably talking about auto-Increment primary key of table rows. Just insert the data, without specifying this "number" and the database will automatically set it to the proper (next free) value.
Do not reuse primary keys (eg you have 1,2,3,4,5 but then delete 3 - if you reuse 3 you will not know at any future point that 3 was some other record that was actually deleted).
This, btw, is very basic database knowledge. Read some introduction tutorials on MySQL or any other SQL relational database.
You are trying to use bad the database.
May be you can look this: Finding the next available id in MySQL
First create a table with values 1 to 9999. Then, run this query once:
delete from table where id IN (select id from profiles)
This way, you get IDs that are not in the profiles table. The first one can be shown to the user. On saving the record, make sure to delete that ID from this table.
If I understood you correctly, this is what you are looking for.
If you are limited to using values 1 through 9999 I would probably setup the process as follows:
Add another table with two columns (id_tracker).
Populate id_tracker with id's 1 through 9999 defaulting is_used to 0.
Update id_tracker.is_used to 1 based on the contents of your table.
Add a delete, insert triggers to your table to update the id_tracker as necesssary.
And select empty ID's as follows SELECT id FROM id_tracker WHERE is_used = 0 ORDER BY id LIMIT 1
Here's some SQL to get you started:
create table id_tracker
(id int not null, is_used tinyint default 0, primary key (id));
delimiter |
CREATE TRIGGER your_table_delete_trigger BEFORE DELETE ON your_table
FOR EACH ROW
BEGIN
UPDATE id_tracker SET is_used = 0 WHERE id = OLD.your_table_id;
END;
|
CREATE TRIGGER your_table_insert_trigger AFTER INSERT ON your_table
FOR EACH ROW
BEGIN
UPDATE id_tracker SET is_used = 1 WHERE id = NEW.your_table_id;
END;
|
delimiter ;
** NOTE: the above is for MySQL

Categories