InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

Menu
  • Home
  • Sitemap

Python Programming Language Best Tutorials and Code Examples

Learn Python Right Now!
Home
PHP
Creating Unique Identifiers in PHP
PHP

Creating Unique Identifiers in PHP

InfinityCoder December 6, 2016

You want to assign unique IDs to users, articles, or other objects as you add them to your database.

Use PHP’s uniqid() function to generate an identifier.

To restrict the set of characters in the identifier, pass it through md5(), which returns a string containing only numerals and the letters a through f.

Example 10-28 creates identifiers using both techniques.
Example 10-28. Creating unique identifiers

1
2
3
$st = $db->prepare('INSERT INTO users (id, name) VALUES (?,?)');
$st->execute(array(uniqid(), 'Jacob'));
$st->execute(array(md5(uniqid()), 'Ruby'));

You can also use a database-specific method to have the database generate the ID. For example, SQLite 3 and MySQL support AUTOINCREMENT columns that automatically assign increasing integers to a column as rows are inserted.

uniqid() uses the current time (in microseconds) and a random number to generate a string that is extremely difficult to guess.

md5() computes a hash of whatever you give it. It doesn’t add any randomness to the identifier, but restricts the characters that appear in it.

The results of md5() don’t contain any punctuation, so you don’t have to worry about escaping issues.

Plus, you can’t spell any naughty words with just the first six letters of the alphabet (in English, at least).
If you’d rather give your database the responsibility of generating the unique identifier, use the appropriate syntax when creating a table.

Example 10-29 shows how to create a table in SQLite with a column that gets an auto-incremented integer ID each time a new row is inserted.

Example 10-29. Creating an auto-increment column with SQLite

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// the type INTEGER PRIMARY KEY AUTOINCREMENT tells SQLite
// to assign ascending IDs
$db->exec(<<<_SQL_
CREATE TABLE users (
   id INTEGER PRIMARY KEY AUTOINCREMENT,
   name VARCHAR(255)
)
_SQL_
);
 
// No need to insert a value for 'id' -- SQLite assigns it
$st = $db->prepare('INSERT INTO users (name) VALUES (?)');
 
// These rows are assigned 'id' values
foreach (array('Jacob','Ruby') as $name) {
   $st->execute(array($name));
}

Example 10-30 shows the same thing for MySQL.
Example 10-30. Creating an auto-increment column with MySQL

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// the AUTO_INCREMENT tells MySQL to assign ascending IDs
// that column must be the PRIMARY KEY
$db->exec(<<<_SQL_
CREATE TABLE users (
   id INT NOT NULL AUTO_INCREMENT,
   name VARCHAR(255),
   PRIMARY KEY(id)
)
_SQL_
);
 
// No need to insert a value for 'id' -- MySQL assigns it
$st = $db->prepare('INSERT INTO users (name) VALUES (?)');
 
// These rows are assigned 'id' values
foreach (array('Jacob','Ruby') as $name) {
   $st->execute(array($name));
}

When the database creates ID values automatically, the PDO::lastInsertId() method retrieves them.

Call lastInsertId() on your PDO object to get the auto-generated ID of the last inserted row.

Some database backends also let you pass a sequence name to lastInsertId() to get the last value from the sequence.

Some database backends don’t support PDO::lastInsertId() at all. In that case, PDO::lastInsertId() causes an error with SQLSTATE set to IM001.

Share
Tweet
Email
Prev Article
Next Article

Related Articles

Writing to Standard Output in PHP
You want to write to standard output. Use echo or …

Writing to Standard Output in PHP

Reading Configuration Files in PHP
You want to use configuration files to initialize settings in …

Reading Configuration Files in PHP

About The Author

InfinityCoder
InfinityCoder

Leave a Reply

Cancel reply

Recent Tutorials InfinityQuest

  • Adding New Features to bash Using Loadable Built-ins in bash
    Adding New Features to bash Using Loadable …
    June 27, 2017 0
  • Getting to the Bottom of Things in bash
    Getting to the Bottom of Things in …
    June 27, 2017 0

Recent Comments

  • fer on Turning a Dictionary into XML in Python
  • mahesh on Turning a Dictionary into XML in Python

Categories

  • Bash
  • PHP
  • Python
  • Uncategorized

InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

About Us

Start learning your desired programming language with InfinityQuest.com.

On our website you can access any tutorial that you want with video and code examples.

We are very happy and honored that InfinityQuest.com has been listed as a recommended learning website for students.

Popular Tags

binary data python CIDR convert string into datetime python create xml from dict python dictionary into xml python how to create xml with dict in Python how to write binary data in Python IP Address read binary data python tutorial string as date object python string to datetime python

Archives

  • June 2017
  • April 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
Copyright © 2021 InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more
Programming Tutorials | Sitemap