Setting the AUTO_INCREMENT of userid - php

guys, how can i set the auto_increment of my userid something like this:
i want to start it in 200, then increment by 10 with a maximum value of 1000..
how will i code it using php?
please help me.. :-(

You can set a starting point to an auto increment value, but the rest you ask (increasing by 10, and limiting at 1000) is impossible on the mySQL level.
You would need to do this in your PHP code, as a pre-check before creating a new user account. Also, I would recommend doing this in a separate, indexed int column.
Update: There is the auto_increment_increment mySQL setting but it seems replication speficic, doesn't apply to your normal, single-database, myISAM setup, and is applied database-wide - it's not what you want.

Related

How do I get the randomly generated primary key of an inserted row in MariaDB/MySQL?

Okay, I am currently developing a website that is supposed to have a searchable database of pool pumps. As part of this system, to prevent people from reading hidden data, I had the primary key of the pool pump stock randomly generated. Here's the code I wrote for the MariaDB backend:
DELIMITER $$
CREATE TRIGGER random_pump_id BEFORE INSERT ON tbl_stock FOR EACH ROW
BEGIN
DECLARE temp_id MEDIUMINT;
REPEAT
SET temp_id = FLOOR(RAND() * 16777216);
UNTIL (SELECT COUNT(*) FROM tbl_stock WHERE pump_id = temp_id) <= 0 END REPEAT;
SET NEW.pump_id = temp_id;
END
$$
But now I've run into a dilemma. Every time I want to insert a row, I need a way to retrieve the primary key I just generated. I know if I used AUTO_INCREMENT I could use the LAST_INSERT_ID function, or lastInsertId in PDO. But since I am not using AUTO_INCREMENT, and instead am using a separate trigger, these functions will only return a 0. I know I can do it in PostgreSQL by using the RETURNING clause, but I can't find a way to accomplish this in MariaDB.
Does anyone know of any solution? Perhaps some obscure trigger I don't know about? Please?
Presumably you have some other way to locate the record? Probably via a UNIQUE key? If so, the fetch the row after adding the random id.
Don't use a trigger, instead write application code. (Triggers can't solve all problems.)

MySQL auto_increment not reseting (stuck on increment by 10)

So running MySQL Version 5.5.42-cll
My tables wherever auto_increment are refusing to reset, they're all incremented by 10 and not by 1.
Tried changing it in phpmyadmin and no luck.
Tried following statement but it didn't work:
ALTER TABLE tablename AUTO_INCREMENT = 1;
Has anyone had this issue before?
I can't truncate the tables as they have a lot of data, I also know that the +10 probably isn't a big deal, but I expect these tables to get large and would rather keep the numbers low and clean.
Any help would be great please
Might be the auto_increment_increment variable. Try this to reset the increment of auto_increment with:
SET ##auto_increment_increment=1;
from MySQL autoincrement column jumps by 10- why?
In phpMyAdmin, log in as a privileged user, go to home page, Variables, type "increment". Then for "auto increment increment", click on Edit, set it to the value you wish (1) and Save.
Old post, but still useful to know. You should not be changing this value, most DBs have a reason for increasing by 10, and it could lead to future issues if you make this change. For more info, check out this post

Reseting mysql autoincrement field value after delete from php?

I have a form from which i am inserting data into mysql works fine.But when i delete some data from mysql, and inserted values into database again the autoincrement value is starting from the previous row value.
ForExample:
If i have 1,2,3,4,5 as id's in mydatabse and if i delete 4 and 5 id's from database
and started inserting next data from PHP. then the id's are coming from 6.... But i need to get id as 4 .can any one give suggestions.Thanks in advance.
I'm afraid MySQL does not allow you to "reset" AUTO_INCREMENT fields like that. If you need that behavior, you have to stop using AUTO_INCREMENT and generate your IDs manually.
Auto increment does not (and cannot) guarantee an unbroken sequence.
You can implement this yourself as "SELECT MAX(ID) + 1 FROM MYTABLE;"
But be warned: You will take a slight but noticeable performance hit.
If you are running updates concurrently you risk deadlocks
(again if you are running updates concurrently) you will risk having two inserts with the same key.
You can also implement this by running your own counter in a separate table. You must have program logic to decrement this correctly on a deletion, and, again you will get a performance hot and risk of deadlock as the "counter" will become an object of contention.
You should not play with AUTO_INCREMENT value in a production environment let MySQL take care of its value for you.
If you need to know how many row you have you can use
SELECT COUNT(id) FROM tbl;
Anyway if you really want to change its value the syntax is :
ALTER TABLE tbl AUTO_INCREMENT=101;

Auto Increment skipping numbers?

Note: I'm new to databases and PHP
I have an order column that is set to auto increment and unique.
In my PHP script, I am using AJAX to get new data but the problem with that is, is that the order skips numbers and is substantially higher thus forcing me to manually update the numbers when the data is inserted. In this case I would end up changing 782 to 38.
$SQL = "INSERT IGNORE INTO `read`(`title`,`url`) VALUES\n ".implode( "\n,",array_reverse( $sql_values ) );
How can I get it to increment +1?
The default auto_increment behavior in MySQL 5.1 and later will "lose" auto-increment values if the INSERT fails. That is, it increments by 1 each time, but doesn't undo an increment if the INSERT fails. It's uncommon to lose ~750 values but not impossible (I consulted for a site that was skipping 1500 for every INSERT that succeeded).
You can change innodb_autoinc_lock_mode=0 to use MySQL 5.0 behavior and avoid losing values in some cases. See http://dev.mysql.com/doc/refman/5.1/en/innodb-auto-increment-handling.html for more details.
Another thing to check is the value of the auto_increment_increment config variable. It's 1 by default, but you may have changed this. Again, very uncommon to set it to something higher than 1 or 2, but possible.
I agree with other commenters, autoinc columns are intended to be unique, but not necessarily consecutive. You probably shouldn't worry about it so much unless you're advancing the autoinc value so rapidly that you could run out of the range of an INT (this has happened to me).
How exactly did you fix it skipping 1500 for ever insert?
The cause of the INSERT failing was that there was another column with a UNIQUE constraint on it, and the INSERT was trying to insert duplicate values in that column. Read the manual page I linked to for details on why this matters.
The fix was to do a SELECT first to check for existence of the value before attempting to INSERT it. This goes against common wisdom, which is to just try the INSERT and handle any duplicate key exception. But in this case, the side-effect of the failed INSERT caused an auto-inc value to be lost. Doing a SELECT first eliminated almost all such exceptions.
But you also have to handle a possible exception, even if you SELECT first. You still have a race condition.
You're right! innodb_autoinc_lock_mode=0 worked like a charm.
In your case, I would want to know why so many inserts are failing. I suspect that like many SQL developers, you aren't checking for success status after you do your INSERTs in your AJAX handler, so you never know that so many of them are failing.
They're probably still failing, you just aren't losing auto-inc id's as a side effect. You should really diagnose why so many fails occur. You could be either generating incomplete data, or running many more transactions than necessary.
After you change 782 in 38 you can reset the autoincrement with ALTER TABLE mytable AUTO_INCREMENT = 39. This way you continue at 39.
However, you should check why your gap is so high and change your design accordingly. Changing the autoincement should not be "default" behaviour.
I know the question has been answered already.. But if you have deleted rows in the table before, mysql will remember the used ID/Number because typically your Auto increment is Unique.. So therefore will not create duplicate increments.. To reindex and increment from the current max ID/integer you could perform:
ALTER TABLE TableName AUTO_INCREMENT=(SELECT max(order) + 1 FROM tablename)
auto increment doesn't care, if you delete some rows - everytime you insert a row, the value is incremented.
If you want a numbering without gaps, don't use auto increment and do it by yourself. You could use something like this to achive this for inserting
INSERT INTO tablename SET
`order` = (SELECT max(`order`) + 1 FROM (SELECT * from tablename) t),
...
and if you delete a row, you have to rearange the order column manually

Setting manual increment value on synchronized mysql servers

I have a mysql\PHP application hosted on intranet and on internet. Both mysql servers are replicated i.e., synchronized on real time.
I have some tables which have auto increment id as primary key. When sync goes off, for new transactions same auto increment value is used on online as well as intranet server.
So even when servers get connected and sync starts; records with same auto increment id do not get sync. Ids with non overlapping values get synced soon the servers get connected.
To resolve this issue, I am thinking of using manual increment values with different range on intranet and online.
Please suggest, what could be the best solution for this problem.
Also if I have to go with manual increment ids, what would be the best technique OR algo to assign ids separately on online and on intranet.
I figured out the solution to this problem.
While configuring the replication of the mysql servers auto increment settings should be adjusted such the ids on the servers never overlap. Example if you have 2 servers replicated one server should only generate even auto increment ID's and other only odd ids.
Here's the link for detail information on this.
http://jonathonhill.net/2011-09-30/mysql-replication-that-hurts-less/
Updating the settings on both the servers resolved this issue.
There are a two things you can do. The first would be to change the starting value of the live server to a very high number (higher then the expected number of rows)
EG:
ALTER TABLE tbl AUTO_INCREMENT = 10000;
Now the numbers wont overlap. If that is not an option you can change the interval with
SET ##auto_increment_increment=10;
But this would also mean there is an overlap at one point. because the server with increment steps of 1 will catch up with the steps of 10 after.. you guessed.. 10 rows!
But you could bypass this by setting one server to start increment at 1 and the other at 2, and then make both have increment steps of 2.
That would make something like
intranet 1, 3, 5, 7, 9
live 2, 4, 6, 8, 10
You could also use a two column primary key to prevent duplication. Now you have an auto increment field in combination with a varchar field (live and intr) and that is your unique key.
CREATE TABLE `casetest`.`manualid` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT ,
`server` VARCHAR( 4 ) NOT NULL DEFAULT 'live',
`name` INT NOT NULL ,
PRIMARY KEY ( `id` , `server` )
) ENGINE = MYISAM ;

Categories