Below is my code that i have written to create a random string. Works well. It also checks to make sure that the generated string doesn't already exist, and if it does, then it makes another one. HOWEVER i haven't yet worked out a way to make the code generated if one already exists be checked to see if that one exists. Would i be best doing an elseif statement?
PHP
<?PHP
require_once('dbConfig.php');
$randomstring = '';
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 12; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
//$generatedId = "SPI-E7HN2SBIIF5W";
$generatedId = 'SPI-'.$randomString;
//Prepare select query
$statement = $db->prepare("SELECT client_unique_id FROM clients WHERE client_unique_id = ? LIMIT 1");
//Determine variable and then bind that variable to a parameter for the select query ?
$id = $generatedId;
$statement->bind_param('s', $id);
//Execute and store result so that num_rows returns a value and not a 0
$statement->execute();
$statement->store_result();
//Bind result to a variable for easy management afterwards
$statement->bind_result($clientId);
// Generate a random ID for the user if the previously generated one already exists
if($statement->num_rows > 0){
$randomstring = '';
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 0; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
$generatedId = 'SPI-'.$randomString;
echo $generatedId;
} else {
// If there's no issue with what's been created, echo it out :)
echo $generatedId;
}
?>
Any help is appreciated :)
try this.
// initialize a variable to hold the last generated id,
$generatedId = '';
// and another to hold the returned client_unique_id,
$clientId = '';
setup your prepared statement
bind the parameter,
$statement->bind_param('s', $id)
do
{
generate a new Id. (Code for generating random id goes here).
$generatedId = '...';
// bind the generated id to the prepared statement.
$id = $generatedId
// execute the prepared statement,
$statement->execute()
// fetch the results into $clientId
$statement->bind_result($res);
while($statement->fetch()) {
$clientId = $res;
}
} while ($clientId != '');
$statement->close();
// echo the last generated Id
echo $generatedId;
cheers,
William
Related
I am trying to generate a unique String with a function. feed the output into a different function that checks a database with PDO to see if that String of characters already exists and then parse it to be entered into a database using PDO. IF for some reason the query comes up positive the function that generates the String gets called again and the process repeats itself. ( on a side note this is why I need this to be done via functions; so I can recall the function over and over if I need to, if you have any better ideas please do share)
my code
$pdo = new PDO("mysql:host=localhost;dbname=notifiyr;charset=utf8mb4", 'root', '', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
$length = 10;
function generatecode($length,$pdo){
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$abc = $randomString;
checkcode($abc);
}
function checkcode($abc){
$sql2 = "SELECT id FROM users WHERE code = :code";
if($stmt = $pdo->prepare($sql2,$abc,$pdo)){
$stmt->bindParam(":code", $param_code, PDO::PARAM_STR);
$param_code = $abc;
if($stmt->execute()){
if($stmt->rowCount() == 1){
generatecode();
} else{
$code = $abc;
}
} else{
$code_err = "something doest want to work here, come back later";
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
}
the problem I am having is that later on in the script I am supposed to enter this along with other variables into the database using PDO all of them enter but the randomly generated string.
edit
I changed my code to this
function generatecode($length,$pdo){
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$abc = $randomString;
return $abc;
}
function checkcode($abc,$pdo){
$sql2 = "SELECT code FROM users WHERE code = :code";
if($stmt = $pdo->prepare($sql2,$abc,$pdo)){
$stmt->bindParam(":code", $param_code, PDO::PARAM_STR);
$param_code = $abc;
if($stmt->execute()){
if($stmt->rowCount() == 1){
generatecode();
} else{
$code = $abc;
return $code;
}
} else{
$code_err = "something doest want to work here, come back later";
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
}
generatecode($length,$pdo);
checkcode($abc,$pdo);
I've had trouble returning functions before in PHP, I hope this code is better
The problem is that you are not using functions correctly, not only are you not parsing items incorrectly you are calling them incorrectly. read the documentation more carefully.
I think you would be want something like this
function generatecode($length,$pdo){
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$abc = $randomString;
return checkcode($abc,$pdo);
}
function checkcode($abc,$pdo){
$sql2 = "SELECT code FROM users WHERE code = :code";
if($stmt = $pdo->prepare($sql2)){
$stmt->bindParam(":code", $param_code, PDO::PARAM_STR);
$param_code = $abc;
if($stmt->execute()){
if($stmt->rowCount() == 1){
generatecode();
} else{
$code = $abc;
return $code;
}
} else{
$code_err = "something doest want to work here, come back later";
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
}
$code = generatecode($length,$pdo);// this correctly calls the function
you're welcome
I need to generate unique username automatically, I've created two functions, one to create a random username and the other one to check if the username is already stored in the database. Do you think these two functions can work?
function km_create_random_username($db_user_conn){
//set the random id length
$km_random_username_length = 6;
//generate a random id encrypt it and store it in $rnd_id
$km_random_username = uniqid(rand(),1);
//to remove any slashes that might have come
$km_random_username = strip_tags(stripslashes($km_random_username));
//Removing any . or / and reversing the string
$km_random_username = str_replace(".","",$km_random_username);
$km_random_username = strrev(str_replace("/","",$km_random_username));
//finally I take the first 6 characters from the $km_rnd_id
$km_random_username = substr($km_random_username,0,$km_random_username_length);
if(!km_check_random_username($db_user_conn, $km_random_username)){
return $km_random_username;
}
}
function km_check_random_username($db_user_conn, $km_random_username) {
$query = "SELECT km_user_username FROM km_users WHERE km_user_username=?";
$stmt = mysqli_prepare($db_user_conn, $query);
mysqli_stmt_bind_param($stmt, 's', $km_random_username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
mysqli_stmt_fetch($stmt);
if($rows > 0) {
km_create_random_username($db_user_conn);
}else{
return false;
}
}
To test that the code spots duplicates and then generates a new randon username do this.
Either empty the table km_user or record the last id value
Run the km_check_random_username() function twice manually passing the same username both time.
km_check_random_username($db_user_conn, 'ItsMee');
km_check_random_username($db_user_conn, 'ItsMee');
Check the table? Did it create the ItsMee username?
Did it create a random username after creating the ItsMe username? If it did, then it spotted the Dup and ran the regenerate phase
echo gen_random_username(10);
// generates jPMNfrQZil
function gen_random_username($db_user_conn, $length){
$chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$random_username = "";
for($i = 0; $i < $length; $i++){
$random_username .= $chars[rand(0,strlen($chars)-1)];
}
if(!km_check_random_username($db_user_conn, $random_username)){
return $random_username;
}
}
// I didn't check this function, but I modified it to use the above function
// gen_random_username($x, $length)...
function km_check_random_username($db_user_conn, $km_random_username) {
$query = "SELECT km_user_username FROM km_users WHERE km_user_username=?";
$stmt = mysqli_prepare($db_user_conn, $query);
mysqli_stmt_bind_param($stmt, 's', $km_random_username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
mysqli_stmt_fetch($stmt);
if($rows > 0) {
gen_random_username($db_user_conn, 10);
}else{
return false;
}
I need to generate a random string when I insert data in my mysql.
I did read about uuid or cast(rand) but I cant find anything that looks like I can use it.
My data comes from a app.
I made a new row called code and made it unik.
I hope you can help me :)
how do I tell my insert to generate a random string to my row code?
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['nummer']) && isset($_POST['description']) && isset($_POST['dato'])) {
$name = $_POST['name'];
$nummer = $_POST['nummer'];
$description = $_POST['description'];
$dato = $_POST['dato'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
mysql_set_charset("utf8");
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, nummer, description, dato) VALUES('$name', '$nummer', '$description', '$dato')");
Ok this is what I got so far
if (isset($_POST['name']) && isset($_POST['nummer']) && isset($_POST['description']) && isset($_POST['dato'])) {
$name = $_POST['name'];
$nummer = $_POST['nummer'];
$description = $_POST['description'];
$dato = $_POST['dato'];
// $code = $_POST['code'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
function generate_random_string($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, nummer, description, dato, code) VALUES('$name', '$nummer', '$description', '$dato', '$randomString')");
But I dont get anything in my code row?
return $randomString;
$random_str = generate_random_string(10);
}
// mysql inserting a new row
$result = mysql_query("INSERT INTO products(name, nummer, description, dato, code) VALUES('$name', '$nummer', '$description', '$dato', '$random_str')");
You can generate a random number using PHP's function rand :
// code = rand($min , $max); for example
code = rand(100000, 999999); // will generate a number between 100000 and 999999
// then add the column to your insert if it belongs to the same table or
// make another query to insert the code if it belongs to a different table
note that you can use the current time and md5 function to make stronger unique codes.
Also, if you like to take this logic to your database, try to create a trigger that will runs after each insert.
Good luck.
You can try the code below:
function generate_random_string($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
echo generate_random_string(15); // define amount of string length in parametre
Source: PHP random string generator
If you use random number as Random String code is below:
$number = range(100000,999999);
shuffle($number);
$ran_string = $number[0];
echo $ran_string;
So like the title says, i've search here and tried almost everything, with no success.
I've try to test something very simple before going more deep, to make sure it works. But even at its simplest, i always get 0 results and i know there are 67 results.
What's wrong with my code?
Thanks
$conn = connect(); // connect to the db
$a_bind_params = array('love', 'circle');
$a_param_type = array('s', 's');
$totalKeywords = count($a_bind_params);
$q = 'SELECT id, name
FROM album
WHERE name LIKE ?';
for ($i = 1; $i < $totalKeywords; $i++) {
$q .= ' AND name LIKE ?';
}
echo $q; // for testing purposes: verify that query is OK
// bind parameters.
$param_type = '';
$n = count($a_param_type);
for($i = 0; $i < $n; $i++) {
$param_type .= $a_param_type[$i];
}
/* with call_user_func_array, array params must be passed by reference */
$a_params = array();
$a_params[] = & $param_type;
for($i = 0; $i < $n; $i++) {
/* with call_user_func_array, array params must be passed by reference */
$a_params[] = & $a_bind_params[$i];
}
$stmt = $conn->prepare($q);
/* use call_user_func_array, as $stmt->bind_param('s', $param); does not accept params array */
call_user_func_array(array($stmt, 'bind_param'), $a_params);
$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;
echo $num_rows; // how many found ?
$stmt->bind_result($id, $name);
while($stmt->fetch()) {
echo $name;
}
$stmt->free_result();
$stmt->close();
$conn->close();
There are not 67 rows with query
SELECT id, name
FROM album
WHERE name LIKE 'love' AND name LIKE 'circle'
There should be OR instead of AND in WHERE clause.
Possibly, you may also need %love% and %circle%?
I have a function that generates a random combination.
my function looks like this:
function random_gen($length) {
$random= "";
srand((double)microtime()*1000000);
$char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$char_list .= "abcdefghijklmnopqrstuvwxyz";
$char_list .= "1234567890";
// Add the special characters to $char_list if needed
for($i = 0; $i < $length; $i++)
{
$random .= substr($char_list,(rand()%(strlen($char_list))), 1);
}
return $random;
}
$new_url = random_gen(6);
Now i would like to have a while-loop that checks if $new_url already exist in my database...
And then insert the result like this:
mysql_query("INSERT INTO lank (url, code) VALUES ('$url', '$new_url')");
I got everything to work except the while-loop. and i just cant figure out how to do it...
define your code field as UNIQUE in your database
generate a code and run an INSERT
check with mysql_affected_rows() if the INSERT actually happened or not (i.e. code already present)
saves you a SELECT query
while ( true ) {
$new_url = random_gen(6);
mysql_query("INSERT INTO lank (url, code) VALUES ('$url', '$new_url')");
if ( mysql_affected_rows() )
break;
}
Use this random_generator
function random_gen($length) {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$string = '';
for ($i = 0; $i < $length; $i++) {
$string .= $characters[rand(0, strlen($characters) - 1];
}
return $string;
}
You don't need a while loop, just perform a query
mysql_query("SELECT COUNT(*) FROM lank WHERE code = {$new_url}");
It's pretty straight forward:
$sql = "SELECT COUNT(*) as num FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
while($row['num'] > 0) {
$new_url = random_gen(6);
$sql = "SELECT COUNT(*) as num FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
}
This should work, without repeating code:
while(true) {
$new_url = random_gen(6);
$sql = "SELECT COUNT(*) FROM lank WHERE code='{$new_url}'";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
if (!$row[0])
break;
}
Use the uniqid() function instead. It will always generate a random result.
If you need more security (i.e.: you don't want adjacent values), simply hash the output: sha1(uniqid()).