Skip to content

Instantly share code, notes, and snippets.

@kerstner
Last active May 10, 2016 13:17
Show Gist options
  • Save kerstner/252c0346a3f52f6d8252 to your computer and use it in GitHub Desktop.
Save kerstner/252c0346a3f52f6d8252 to your computer and use it in GitHub Desktop.
Generate 6 Character Random Bit.ly like ID for a URL with PHP and MySQL
// Set number of shortcodes to generate
$shortcodes = 10000000;
// Loop through and create unique shortcodes
while ($shortcodes) {
$shortcode = generateShortcode();
$checkSQL = "SELECT shortcode FROM shortcodes WHERE shortcode = '" . $shortcode . "'";
$checkResult = $mysqli->query($checkSQL);
// If doesn't exist, insert into database
if ($checkResult->num_rows == 0) {
$sql = "INSERT IGNORE INTO shortcodes (shortcode) VALUES ('" . $shortcode . "')";
$mysqli->query($sql);
echo "Inserted Shortcode: " . $shortcode . "\r\n";
$shortcodes--;
}
}
// Function to generate shortcode
function generateShortcode() {
$shortcode = substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(0,61), 1) .
substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(0,61), 1) .
substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(0,61), 1) .
substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(0,61), 1) .
substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(0,61), 1) .
substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(0,61), 1);
return $shortcode;
}
@kerstner
Copy link
Author

kerstner commented Oct 6, 2014

On a server with only 512MB of RAM you should still get 1,000-2,500 inserts a second

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment