I want to populate a table that has the next structure:
USERS_TABLE
ID_USR (Primary_Key, AUTO_INCREMENT)
USERNAME (Not Null)
EMAIL (Not Null, Unique Key)
Password(Not Null)
Nacionality (Not Null)
Work (Null)
And I want to do it with a php script. It's not a problem for me to create the script but I have some doubts with the email's field. I don't want real names or emails, just data and the posibility to introduce over 10-100 rows.
So with the ID_USR I don't have problems because it's an auto increment value, no problems with the not null's or null's fields.
Now think about the email, as you see it is a unique key so I thought about putting two random numerical values, one before and one after # and then the extension.
Example:
<?php
for ($i = 0; $i < 10; $i++)
{
$a = rand();
$b = rand(); // array("gmail", "facebook", "hotmail", "outlook", "yahoo".....);
$extension = array(".com", ".es", ".net", ".org"); // ....
$c = rand(0,3);
$email = $a."#".$b."".$extension[$c];
echo "$email";
}
?>
It returns to me:
2095518299#699790428.com
254450939#1623171070.org
1142680888#2074501004.org
1940419404#1779299580.es
726585010#1262850036.net
578544275#145818927.net
2067281904#1894405902.org
275443932#1915863743.es
734209458#1269004984.com
1035465063#1828742272.net
As you can see this can work but my question is if there is a smarter/efficient way.
I think this may be constructive so I hope your answers. See you.
Aha, the test data problem!
If I were you I'd use a domain name you control for the domain part of the email addresses. That is,
726585010#emailtest.yoyodyne.com
578544275#emailtest.yoyodyne.com
2067281904#emailtest.yoyodyne.com
(if you happen to work for Yoyodyne.) This will prevent randomly generated email addresses from escaping into the wild if you should make an error and try to send to everybody.
Then, use a longer random number for the number so you don't get many accidental collisions. You will probably will get some.
Finally, after you populate the table, before you use it, go back and change the email column so it incorporates the id number.
UPDATE USERS_TABLE SET EMAIL = CONCAT(ID_USR,'#emailtest.yoyodyne.com')
That way your tests will be readily traceable back to particular user rows.
Related
I have a requirement where I need to insert user_id in following format
13310_userid_1
13310_userid_2
13310_userid_3
where
13310 = $_GET['userid'] //user id from session
userid = constant //constant text defined
1/2/3 = autoincrement value
Here the variation is when user_id is changed, the auto increment value will be inserted from beginning which would look like
13311_userid_1
13311_userid_2
13311_userid_2
and not
13311_userid_4
13311_userid_5
13311_userid_6
How can I check if the user_id is changed and insert auto increment value from 1 ?
Thanks
I'm not sure it's that you need, but you can use an array to store increment of each cont :
$const = 'userid';
$user_id = '13310';
$array_increment[$user_id] =1;
foreach(array('Franck','Robert','You','Me') as $index=>$test){
if($index==2)$user_id = '13311';
if(!isset($array_increment[$user_id])){
$array_increment[$user_id]=1;
}
$increment = $array_increment[$user_id];
echo $user_id.'_'.$const.'_'.$increment.'<br />';
$array_increment[$user_id]++;
}
Will show :
13310_userid_1
13310_userid_2
13311_userid_1
13311_userid_2
you could store the incremental value of each userid in a temporary session:
For each request check if $_GET['userid'] already exists in a session if not create it with value zero.
Increment by one and use this value to create your string for inserting into DB
//set up session if it is not already set
if(!isset($_SESSION['users'][$_GET['userid'])){
$_SESSION['users'][$_GET['userid']=0;
}
$_SESSION['users'][$_GET['userid']=$_SESSION['users'][$_GET['userid']+1;
$user=$_GET['userid'].'_userid_'.$_SESSION['users'][$_GET['userid'];
//insert $user into your DB or permanent storage.
$db->insert($user);
(this should be a comment but its a bit verbose)
Your only makes sense if a database figures in here somewhere - but you never explicitly stated that this is the case nor which database it is.
Relational database design (and to quite a large extent, non-relational database design) is subject to the rules of normalization. These are methods for describing the structure of your data and prevent you doing stupid things. This breaks the first rule.
Assuming you were designing the system properly, then you would keep the three attributes as seperate fields. But that does not answer the question of whether the id is nominal, cardinal or ordinal (and in the case of ordinal numbers whether there is a requirement for them to be consecutive).
usersim interested how do i select a text field form my mysql database, i have a table named users with a text field called "profile_fields" where addition user info is stored. How do i access it in php and make delete it? I want to delete unvalidate people.
PHP code
<?php
//Working connection made before assigned as $connection
$time = time();
$query_unactive_users = "DELETE FROM needed WHERE profile_fields['valid_until'] < $time"; //deletes user if the current time value is higher then the expiring date to validate
mysqli_query($connection , $query_unactive_users);
mysqli_close($connection);
?>
In phpmyadmin the field shows (choosen from a random user row):
a:1:{s:11:"valid_until";i:1370695666;}
Is " ... WHERE profile_fields['valid_until'] ..." the correct way?
Anyway, here's a very fragile solution using your knowledge of the string structure and a bit of SUBSTRING madness:
DELETE FROM needed WHERE SUBSTRING(
profile_fields,
LOCATE('"valid_until";i:', profile_fields) + 16,
LOCATE(';}', profile_fields) - LOCATE('"valid_until";i:', profile_fields) - 16
) < UNIX_TIMESTAMP();
But notice that if you add another "virtual field" after 'valid_until', that will break...
You can't do it in a SQL command in a simple and clean way. However, the string 'a:1:{s:11:"valid_until";i:1370695666;}' is simply a serialized PHP array.
Do this test:
print_r(unserialize('a:1:{s:11:"valid_until";i:1370695666;}'));
The output will be:
Array ( [valid_until] => 1370695666 )
So, if you do the following, you can retrieve your valid_until value:
$arrayProfileData = unserialize('a:1:{s:11:"valid_until";i:1370695666;}');
$validUntil = arrayProfileData['valid_until'];
So, a solution would be to select ALL items in the table, do a foreach loop, unserialize each "profile_fields" field as above, check the timestamp, and store the primary key of each registry to be deleted, in a separate array. At the end of the loop, do a single DELETE operation on all primary keys you stored in the loop. To do that, use implode(',', $arrayPKs).
It's not a very direct route, and depending on the number of registers, it may not be slow, but it's reliable.
Consider rixo's comment: if you can, put the "valid_until" in a separate column. Serializing data can be good for storage of non-regular data, but never use it to store data which you may need to apply SQL filters later.
I am planning to build, for lack of a better term, a multi user Customer Relationship Manager (CRM) and I want to create a unique identifier that is easy to transmit in email, via text, and verbally to other team members.
For Example:
I upload my list of 100 customers and John Smith and his phone number are included in that list. Upon upload, I want to generate a hidden fingerprint / unique identifier for John Smith in the database, and then propagate a 12 digit number that can be shared publicly.
In my mind like this - john smith + ph: 5557898095 = fingerprint: 7e013d7962800374e6e67dd502f2d7c0 displays to end user id number: 103457843983
My question is - what method or process should I use to take the name and phone number, generate a hidden key, and then translate to a displayable key that is linked to the hidden one?
I hope this clear. I mainly want to use the right logic process.
You could use crc32('fingerprint') for the end user id number:
<?php
echo printf("%u", crc32('7e013d7962800374e6e67dd502f2d7c0')); //226407465310
?>
I don't understand what your problem really is, but I'll try.
It seems like you mean something like this:
A SQL table which saves the public and private ID (and maybe other things).
You can generate a key like this:
$chars = '0123456789abcedfghijklmnopqrstuvwxyz';
function generateKey($length, $charsLength = 10) {
global $chars;
$key = '';
for($i=0;$i<$length;++$i) {
$key .= $chars[rand(0, $charsLength - 1)];
}
return $key;
}
$keyPublic = generateKey(10); // Public key with length 10
// Now check if the key already exist
while(mysql_num_rows(mysql_select('SELECT publicKey FROM keys WHERE publicKey = \''.$keyPublic.'\')) === 1) {
$keyPublic = generateKey(10);
}
$keyPrivate = generateKey(10, 36); // Private key with length 10
// Now check if the key already exist
while(mysql_num_rows(mysql_select('SELECT privateKey FROM keys WHERE privateKey = \''.$keyPrivate.'\')) === 1) {
$keyPrivate = generateKey(10, 36);
}
In this example there are two keys generated and it is checked if the keys already exist. (in the example in the table "keys").
Assuming your real ID is the auto_incremented field in your customer table, then just have a second table that maps your public ID to the real ID.
Assuming you're using some sort of hashing algorithm to generate your public ID, it'd be a simple process to do a lookup on that table when you create a new user to detect a clash with an existing user, then regenerate a new ID until there's no clash (e.g. include system time as part of your hash input, then just keep regenerating until you find a unique ID)
I'm trying to generate a unique "dosieid" number for my web site. My web site is a human resources program solution, in that program users create dosie of their workers in their firm ...random dosieid needs me so when user creating dosie in field dosieid automatically show the dosieid-s that are not used before...the dosieid that don't exist in database. In other case I would use auto increment but in this case dosie is not created yet. And in form dosieid must be option to change the number if random is not fine with a user. One more hint the numbers must bee from 1 to 9999. Can someone help me? I have try many codes but I have not find something like one with this spec.
This is what I have do so far. It gets the random number but I don't know how to compare that random number with database row "dosieid" ?
$id_num = mt_rand(1,9999);
$query = "SELECT dosjeid FROM albums";
$result = mysql_query($query) or die(mysql_error());
while($account = mysql_fetch_array($result)){
if ($id_num == $account['id']){
$id_num = mt_rand(1,9999);
}
}
echo"$id_num<br>";
This is extraordinarily convoluted... why is an auto-incrementing number not enough? This code would also never work properly. If for whatever reason you HAVE to use a random number, then you'd do it like this:
while(true) {
$id_rand = mt_rand(1,9999);
$result = mysql_query("SELECT count(*) FROM albums WHERE dosjeid=$id_rand") or die(mysql_error());
$row = mysql_fetch_row($result);
if ($row[0] == 0) {
break; // our random number isn't in the database, so exit the loop
}
}
However, here's some problems with this:
1) You'll get an infinite loop when you reach 9999 dosie records
2) The more records there are in the database, the longer this loop will take to find a "vacant" slot. As you get closer and closer to 9999 records, you'll be taking a LONG time to find that one empty slot
3) If you're trying to "cloak" the IDs of anyone member so that users can't simply increment an ID parameter somewhere to see other people's records, there's FAR FAR FAR better/easier ways of doing this, such as encrypting the ID value before sending it out to clients.
Use a auto-increment number as your primary key and an additional display id with the UNIQUE attribute as the ID shown to the user. This way you have a unique ID for your internal processing and a display ID that can be easily changed.
This is a terrible design. You should either:
not let users create the dosieid (create it yourself, give it to them after record created)
Try to create a stub record first with an assigned dosieid, and then update it with information
or use UUIDs, which requires a much bigger range than 1-9999
Even if you check that the number was unique, in between the time when you check it and the time you insert the record someone else may have taken it.
And under no circumstances should you find an empty id by picking numbers at random. This makes your program execution time non-deterministic, and if you eventually get 5000 employees you could be waiting a long time.
Also, This range is way too small for a randomness requirement.
You may also want to read about number only hashes (check upon the algorithm's collision rate) - php: number only hash?
function doesIdExists($id)
{
$query = "SELECT dosjeid FROM albums";
$result = mysql_query($query) or die(mysql_error());
while($account = mysql_fetch_array($result))
{
if ($id_num == $account['id'])
return true; /* The id is taken */
}
return false; /* Not taken */
}
$recNotAdded = true;
while($recNotAdded)
{
$rand = mt_rand(1,1000); //Whatever your numbers
$doesExist = doesIdExists($rand);
if(!$doesExist)
{
/* Add to DB */
$recNotAdded = false;
}
}
I am developing a mysql database.
I "need" a unique id for each user but it must not auto increment! It is vital it is not auto increment.
So I was thinking of inserting a random number something like mt_rand(5000, 1000000) into my mysql table when a user signs up for my web site to be. This is where I am stuck?!
The id is a unique key on my mysql table specific to each user, as I can not 100% guarantee that inserting mt_rand(5000, 1000000) for the user id will not incoherently clash with another user's id.
Is there a way in which I can use mt_rand(5000, 1000000) and scan the mysql database, and if it returns true that it is unique, then insert it as the user's new ID, upon returning false (somebody already has that id) generate a new id until it becomes unique and then insert it into the mysql database.
I know this is possible I have seen it many times, I have tried with while loops and all sorts, so this place is my last resort.
Thanks
You're better off using this: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid
Or using this: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
But if you actually want to do what you are saying, you can just do something like:
$x;
do {
$x = random_number();
"SELECT count(*) FROM table WHERE id = $x"
} while (count != 0);
// $x is now a value that's not in the db
You could use a guid. That's what I've seen done when you can't use an auto number.
http://php.net/manual/en/function.com-create-guid.php
Doesn't this function do what you want (without verification): http://www.php.net/manual/en/function.uniqid.php?
I think you need to approach the problem from a different direction, specifically why a sequence of incrementing numbers is not desired.
If it needs to be an 'opaque' identifier, you can do something like start with a simple incrementing number and then add something around it to make it look like it's not, such as three random numbers on the end. You could go further than that and put some generated letters in front (either random or based on some other algorithm, such as the day of the month they first registered, or which server they hit), then do a simple checksuming algorithm to make another letter for the end. Now someone can't easily guess an ID and you have a way of rejecting one sort of ID before it hits the database. You will need to store the additional data around the ID somewhere, too.
If it needs to be a number that is random and unique, then you need to check the database with the generated ID before you tell the new user. This is where you will run into problems of scale as too small a number space and you will get too many collisions before the check lucks upon an unallocated one. If that is likely, then you will need to divide your ID generation into two parts: the first part is going to be used to find all IDs with that prefix, then you can generate a new one that doesn't exist in the set you got from the DB.
Random string generation... letters, numbers, there are 218 340 105 584 896 combinations for 8 chars.
function randr($j = 8){
$string = "";
for($i=0;$i < $j;$i++){
srand((double)microtime()*1234567);
$x = mt_rand(0,2);
switch($x){
case 0:$string.= chr(mt_rand(97,122));break;
case 1:$string.= chr(mt_rand(65,90));break;
case 2:$string.= chr(mt_rand(48,57));break;
}
}
return $string;
}
Loop...
do{
$id = randr();
$sql = mysql_query("SELECT COUNT(0) FROM table WHERE id = '$id'");
$sql = mysql_fetch_array($sql);
$count = $sql[0];
}while($count != 0);
For starters I always prefer to do all the randomization in php.
function gencode(){
$tempid=mt_rand(5000, 1000000);
$check=mysql_fetch_assoc(mysql_query("SELECT FROM users WHERE id =$tempid",$link));
if($check)gencode();
$reg=mysql_query("INSERT INTO users id VALUES ('$tempid')",$link);
//of course u can check for if $reg then insert successfull