I have this function which creates random string:
function genID($length) {
$chars = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM#!";
//only allowed chars in the blowfish salt.
$size = strlen($chars); $str = "";
for ($i = 0; $i < $length; $i++)
$str .= $chars[rand(0, $size - 1)]; // strings can be used as char arrays
// Yes, I am aware this salt isn't generated using the OS source.
// use mycrypt_create_iv or /dev/urandom/
return $str;
}
This output something like:
#iBUQvldLq
Now I have users list with something like that:
userid | username | usermail ...
--------------------------------------
#iBUQvldLq test test#gmaik.com ....
Now when some one register I create new string and insert the new string to userid row in database, after that I create a new string, then I check if the new string created doesn't exist, something like this:
function newID()
{
$newid = genID(10);
$query = "SELECT * FROM users WHERE userid = '".$newid."'";
$result1 = mysql_query($query);
$num = mysql_num_rows($result1);
if($num == 1)
{
$newid = genID(10);
return $newid;
}
else
{
return $newid;
}
}
Any one have any idea how to loop on the check function?
I mean the generate function create new random string, then the function check if it already exist, then create new one, if not return the one created.
So now if he create new one, and the new one also match the same other userid, so how I loop until the new string won't match never to other userid string?
Something like loop:
create new string
verify if exist
if exist create new one
if the new one also exist create new one and so on
Till its never match other userid, make a loop, any idea ?
EDITED :
The new function for loop if any need:
function newID(){
$continue = true;
while ($continue) {
$newid = genID(10);
$query = mysql_query("SELECT * FROM users WHERE userid='".$newid."' LIMIT 1");
if (mysql_num_rows($query) != 1)
$continue = false;
return $newid;
}
}
$newid = newID();
It looks like your wanting code like this..
function uHash(){
$continue = true;
while ($continue) {
$hash = substr(MD5(microtime()), 0, 7);
$query = mysql_query("SELECT `Link` FROM Table WHERE `value`='$hash' LIMIT 1");
if (mysql_num_rows($query) != 1)
$continue = false;
return $hash;
}
}
The script will loop until it finds a unique value.
Setting your user_id column as an auto_increment field would solve this issue. [Best Approach]
If you really want to do with PHP, couple uniqid() with rand() to generate a unique seed that doesn't collide.
Something like this
<?php
echo $id = uniqid(rand(), true);
?>
Just you can use for unique id
<?php
function genID() {
return uniqid();
}
echo genID();
?>
Related
am having a problem with a bit of code.
I am trying to generate a unique name to insert into a database.
i have created the following function which checks to see if the name already exists:
function checkExists($database_reelfilm, $reelfilm, $mySlug, $locVal){
$mmid_rs_slugCheck = "-1";
if (isset($mySlug)) {
$mmid_rs_slugCheck = $mySlug;
}
$mmid2_rs_slugCheck = "-1";
if (isset($locVal)) {
$mmid2_rs_slugCheck = $locVal;
}
mysql_select_db($database_reelfilm, $reelfilm);
$query_rs_slugCheck = sprintf("SELECT * FROM locations_loc WHERE locations_loc.slug_loc = %s AND locations_loc.id_loc != %s", GetSQLValueString($mmid_rs_slugCheck, "text"),GetSQLValueString($mmid2_rs_slugCheck, "int"));
$rs_slugCheck = mysql_query($query_rs_slugCheck, $reelfilm) or die(mysql_error());
$row_rs_slugCheck = mysql_fetch_assoc($rs_slugCheck);
$totalRows_rs_slugCheck = mysql_num_rows($rs_slugCheck);
if($totalRows_rs_SlugCheck > 0){
return true;
}else{
return false;
}
};
i then create a loop to checking if the variable name exists, if it does i want it to add the value of the counter to the variable name then recheck to see if that exists until i have a unique name which i can then save to my db.
$updateVal = slugify($row_rs_locations['name_loc']);
$newSlug = slugify($row_rs_locations['name_loc']);
$locVal = $row_rs_locations['id_loc'];
//echo(slugify($row_rs_locations['name_loc']));
$checkCount = 1;
$isDupe = '<BR>';
while(checkExists($database_reelfilm, $reelfilm, $newSlug, $locVal)){
$isDupe = 'Duplicate Added ' . $checkCount . ' to slug...<BR>';
$newSlug = $newVal . $checkCount;
$checkCount ++;
}
if($updateVal != $newVal){
$updateVal = $newSlug;
}
I am obviously doing something wrong, I need the while loop on the next iteration to use the newSlug value set in the loop, from my various attempts i am not at all sure if this is possible.
Whats the best way to accomplish this?
$newVal is not ever given a value, but it is used twice (second block of code). I think you need something like:
$newSlug = slugify($row_rs_locations['name_loc']);
$newVal = $newSlug;
i need the while loop on the next iteration to use the newSlug value
set in the loop
In the while loop you do
$newSlug = $newVal . $checkCount;
But $newVal does not exist. Replace that line with the following:
$newSlug .= $checkCount;
This question already exists:
Closed 10 years ago.
Possible Duplicate:
same roll number can not be added
I want my code to behave this way that if once i had added a roll number, it can not be added again in the registration..........same as if once an email adress is registered the error displays that EMAIL ADDRESS ALREADY BEEN TAKEN....
I am creating a function . of roll numbr value is 1 it shall display error and if not 1 it shall not display the error
function selectroll($studentname,$rollnumber)
{
$sql = "SELECT * FROM tblstuden WHERE studentname = 'studentname' and rollnumber = '$rollnumber';";
$obj_db = new DB();
$obj_db->query($sql);
$row = $obj_db->rsset();
if{
$val = 1;
}
else{
$val = 0;
}
$obj_db->db_close();
return $val;
}
$this->_id($row[id]);
$this->_studentname($row[studentname]);
$this->_rollnumber($row[rollnumber]);
$this->_classname($row[classname]);
$obj_db->db_close();
}
}
?>
and the function is called at the page by this method
<?php
if(isset($_POST['btnSubmit']) and $_GET['action'] == "Add")
{
$val = $Tblstuden->selectroll($_POST['studentname'],$_POST['rollnumber']);
if ($val =='1')
{
$Tblstuden->copyPostData();
$Tblstuden->insert();
echo"asdf";
}
redirect("index.php?page=studentlist");
}
else
{
echo"abc";
}
?>
You probably want
function selectroll($studentname,$rollnumber)
{
$sql = "SELECT * FROM tblstuden WHERE studentname = 'studentname' and rollnumber = '$rollnumber';";
$obj_db = new DB();
$obj_db->query($sql);
$row = $obj_db->rsset();
if ($row){
$val = 1;
$this->_id($row[id]);
$this->_studentname($row[studentname]);
$this->_rollnumber($row[rollnumber]);
$this->_classname($row[classname]);
}
else{
$val = 0;
}
$obj_db->db_close();
return $val;
}
}
?>
in line 8 of the top function - as otherwise the code won't compile.
Sub-note, your code is subject to mysql injection, you should look at using PDO (http://php.net/manual/en/book.pdo.php) for your database functions before you get used to the old method. Please. Do it now ;)
This question already has answers here:
Filter multidimensional array based on partial match of search value
(3 answers)
Closed 1 year ago.
I have some code that takes from a txt file a list of emails and inserts them into a database, making sure not to add the email if it's already in said database. What I'm trying to do now is filter emails as they are read from the txt file and NOT insert them if they are an exact or partial match to any strings within the $filter array. In other words, if the email has 'gmail', '.ru' or 'exec' anywhere within the email address, I don't want it added.
Any help to stop the bleeding from me pounding my head against a wall would be great!
The code:
$TheFile = "emails.txt";
$handle = fopen($TheFile, 'r');
$good_count = 0;
$bad_count = 0;
$filter= array("gmail",".ru","exec");
while (!feof($handle))
{
$Data = fgets($handle, 1024);
$output = explode (",",$Data);
$exist = mysql_query("SELECT * FROM table WHERE email='$output[0]'");
if (mysql_num_rows ($exist) == 0) {
$email = strtolower($output[0]);
$sql = "INSERT INTO table SET email='$email'";
mysql_query($sql);
$good_count = $good_count + 1;
}
else {
$bad_count = $bad_count + 1;
}
}
Use stripos in a validation function:
function validate_email($input, array $needles) {
foreach ($needles as $needle) {
if (stripos($input, $needle) === false) return false;
}
return true;
}
// ...
if (mysql_num_rows ($exist) == 0 &&
validate_email($output[0], $filter))
{
$email = strtolower($output[0]);
$sql = "INSERT INTO table SET email='$email'";
mysql_query($sql);
$good_count = $good_count + 1;
}
else {
$bad_count = $bad_count + 1;
}
Also, consider using a UNIQUE index in your table definition. This will cause a (catchable) MySQL error if the email already exists and will offload your script from doing a SELECT query for every email in your file.
I am generating unique id for my small application but I am facing some variable scope problem. my code-
function create_id()
{
global $myusername;
$part1 = substr($myusername, 0, -4);
$part2 = rand (99,99999);
$part3 = date("s");
return $part1.$part2.$part3;
}
$id;
$count=0;
while($count == 1)
{
$id;
$id=create_id();
$sqlcheck = "Select * FROM ruser WHERE userId='$id';";
$count =mysql_query($sqlcheck,$link)or die(mysql_error());
}
echo $id;
I dont know which variable I have to declare as global
That doesn't look like a variable scope problem, it looks like a simple variable assign problem:
$count=0;
while($count == 1)
{
This block will clearly never execute.
Further, please use a boolean with a good name when doing boolean checks. It reads so much cleaner. i.e.:
function isUniqueUserID($userIDToCheck)
{
$sqlcheck = "Select * FROM user WHERE userId='$userIDToCheck';";
$resource = mysql_query($sqlcheck)or die(mysql_error());
$count = mysql_fetch_assoc($resource);
if( count($count) > 0)
{return false;}
return true;
}
$userIDVerifiedUnique = false;
while(! $userIDVerifiedUnique )
{
$userIDToCheck = create_id();
$userIDVerifiedUnique = isUniqueUserID($userIDToCheck );
}
Note that mysql_query will use the last used connection if you don't specify a link:
http://us2.php.net/mysql_query
No need to make it global.
in adition to Zak's answer i'd pass the username into the function instead of using globals
function create_id($username)
{
$part1 = substr($username, 0, -4);
$part2 = rand (99,99999);
$part3 = date("s");
return $part1.$part2.$part3;
}
also
//$id; no need for this
$count=1; // this bit
while($count == 1) // not sure what's going on
{
//$id; again same thing no need for this
$id=create_id($myusername);
edit: now that i think of it: how do you expect to find "Select * FROM ruser WHERE userId='$id';"? A Select query is used to find something specific, your username is so random, i think the likely hood of actually successfully getting a record is 1 in a bajillion.
edit2 whoops, i see the whole point is to get a unique username... O_O
In addition to the others:
$count =mysql_query($sqlcheck,$link)or die(mysql_error());
mysql_query doesn't return a record count but, rather, a resource.
mysql_query
my code-
function create_id()
{
//global $myusername;
$part1 = substr("Piyush", 0, -4);
$part2 = rand (99,99999);
$part3 = date("s");
return $part1.$part2.$part3;
}
echo create_id(); //this is printing fine.
function isUniqueUserID($userIDToCheck)
{
$sqlcheck = "Select * FROM ruser WHERE userId='$userIDToCheck';";
$resource = mysql_query($sqlcheck)or die(mysql_error());
$count = mysql_fetch_assoc($resource);
if( count($count) > 0)
{return false;}
return true;
}
$userIDVerifiedUnique = false;
while(! $userIDVerifiedUnique )
{
$userIDToCheck = create_id();
$userIDVerifiedUnique = isUniqueUserID($userIDToCheck );
}
loop is just going on and on from while loop to function IsUniqueUser() and vice versa.????
If there are no rows returned from the MySQL query (i.e. the $userIDToCheck is not in the table, it is unique) then mysql_fetch_assoc will return FALSE. When that happens, count(FALSE) returns 1 (one)! Since that value is greater than zero the function returns FALSE.
In short, if there is a row returned (the string is not unique) your isUniqueUserID function returns FALSE; if there is no row returned (the string is unique) it still returns FALSE.
A simple, new, function to check on the database table could look something like the following...
function isUniqueUserID($userIDToCheck)
{
$userIDToCheck = mysql_real_escape_string($userIDToCheck); // Assume not already escaped
$sqlcheck = "SELECT 1 FROM ruser WHERE userId='$userIDToCheck' LIMIT 1";
$resource = mysql_query($sqlcheck) or die(mysql_error());
return (bool) mysql_num_rows($resource);
}
First, try changing your isUniqueUserID() function to this
function isUniqueUserID($userIDToCheck)
{
$userIDToCheck = mysql_real_escape_string($userIDToCheck); //prevent SQL injection
$sqlcheck = "Select userId FROM ruser WHERE userId='$userIDToCheck';";
$resource = mysql_query($sqlcheck)or die(mysql_error());
$count = mysql_num_rows($resource);
return ($count > 0) ? false : true;
There's no point in returning an associative array just to count the number of rows in it. And there's no point in doing a SELECT * when counting just do SELECT userId since that's all you're concerned with.
I don't see any other reason that isUniqueUserID() would return false unless your ruser table has every possible ID.