Last active
May 10, 2016 13:17
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On a server with only 512MB of RAM you should still get 1,000-2,500 inserts a second