php - MySQLi creating random string, but checking it doesn't already exist -
below code have written create random string. works well. checks make sure generated string doesn't exist, , if does, makes one. haven't yet worked out way make code generated if 1 exists checked see if 1 exists. best doing elseif statement?
php
<?php require_once('dbconfig.php'); $randomstring = ''; $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; ($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 clients client_unique_id = ? limit 1"); //determine variable , bind variable parameter select query ? $id = $generatedid; $statement->bind_param('s', $id); //execute , store result num_rows returns value , not 0 $statement->execute(); $statement->store_result(); //bind result variable easy management afterwards $statement->bind_result($clientid); // generate random id user if generated 1 exists if($statement->num_rows > 0){ $randomstring = ''; $characters = '0123456789abcdefghijklmnopqrstuvwxyz'; ($i = 0; $i < 0; $i++) { $randomstring .= $characters[rand(0, strlen($characters) - 1)]; } $generatedid = 'spi-'.$randomstring; echo $generatedid; } else { // if there's no issue what's been created, echo out :) echo $generatedid; } ?>
any appreciated :)
try this.
// initialize variable hold last generated id, $generatedid = ''; // , hold returned client_unique_id, $clientid = ''; setup prepared statement bind parameter, $statement->bind_param('s', $id) { generate new id. (code generating random id goes here). $generatedid = '...'; // bind generated id prepared statement. $id = $generatedid // execute prepared statement, $statement->execute() // fetch results $clientid $statement->bind_result($res); while($statement->fetch()) { $clientid = $res; } } while ($clientid != ''); $statement->close(); // echo last generated id echo $generatedid;
cheers,
william
Comments
Post a Comment