Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, generate string with format, check against SQL db? [closed]

Tags:

sql

php

I'm trying to use PHP as a way to process this in a webpage, my typical language is java so i am unfamiliar with how this would be done for product keys.

This is basically the process:

1. Generate random string with format XX-XXXX-XXXX-XXX a mix of numbers and letters.
2. Check if it already exists in an SQL database
3. If exists, generate another one and repeat?

So how would I do this using PHP? Please explain what i would need to do and what is the best way of going about it.

like image 982
user2816960 Avatar asked Oct 18 '25 13:10

user2816960


2 Answers

Generate random string from following function.

<?php
function randomString() {
    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    $array_lengths = array(2,4,4,3);
    foreach($array_lengths as $v){
      for ($i = 0; $i < $v; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
      }
      $pass[] = '-';
    }
    return rtrim(implode($pass),'-'); //turn the array into a string
}

echo randomString();

?>

SQL Please create unique key field and use ON DUPLICATE KEY query for insert/ update data

DEMO

like image 110
Girish Avatar answered Oct 21 '25 02:10

Girish


You can generates randomnumbers key using this way.

echo rk(2)."-".rk(4)."-".rk(4)."-".rk(3);
function rk($chars) {
   $letters = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
   return substr(str_shuffle($letters), 0, $chars);
}
like image 39
Rahul K Avatar answered Oct 21 '25 02:10

Rahul K