Skip to content
Advertisement

generate a unique hash value which can be used as primary key in mysql thru php

I am using auto increment value for the inserts in my table. But is there any other way to generate a unique value (which is small enough and not GUID or UUID) in php to insert as primary key in mysql?

Basically I want to get the value that is used as PK, but using auto increment I guess I cannot get the next auto increment value?

Please suggest me something on this?

Thanks.

Advertisement

Answer

You can get the last inserted autoincrement value. You want the mysql_insert_id function:

<?php
    mysql_query("INSERT INTO mytable (product) values ('blah')");
    printf("Last inserted record has id %dn", mysql_insert_id());
?>

The problem with having PHP generate a hash and using that as a primary key is that the hash generated could (albeit probably very rarely) be a duplicate key. Thus, you’d have to check to see if the hash is already in use, and generate more until it isn’t in use.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement