Skipping primary key number when querying primary value before insert
I suspect the answer to this is very simple, but for whatever reason, I'm
a bit baffled by it.
I am trying to generate a unique 20 char alphanumeric hash value. I have
tried multiple ways to generate a random value via PHP, but I am still
getting duplicates. I was temporarily trying a process in which I query
the table before the insert, pull the most recent primary key value,
increase it by one and then use that as part of the generated hash value.
Unfortunately, the below code results in the following insert of the
primary key increasing by 2 instead of 1 (i.e. 13, 15, 17, 19, etc.)
Here is my code:
$dbTableNumQuery = $dbh->prepare("SELECT ROW_ID FROM table ORDER BY ROW_ID
DESC LIMIT 1");
$dbTableNumQuery->execute();
$dbTableNumRow = $dbTableNumQuery->fetch();
$lastID = $dbTableNumRow['ROW_ID'];
$lastID = intval($lastID);
$lastID = $lastID + 1;
$hash =
substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"),
0, 20);
$hash = $lastID . $hash;
$hash = substr($hash, 0, 20);
$query = $dbh->prepare("INSERT INTO secondarytable (HASH) VALUES (:hash)");
$query->bindParam(':hash', $hash, PDO::PARAM_STR);
$status = $query->execute();
What confuses me the most is that I don't understand why the value of the
primary key is increasing by 2, when I am not specifying its value in my
insert query.
And help would be greatly appreciated.
No comments:
Post a Comment