hello guys i need your help please
iam creating a form which store data into mysql database and every thing is good tell now.
i need to generate a code for each member fill in the form this code i need it to be like ( SUD001 ) i want it to be unique and auto increasing one i means first one fill in the form get code of (SUD001) second one gets (SUD002) thread (SUD003) and so on.
what i need is a way to do that and then insert that code into mysql database, i got no problem in inserting it into the data base but i need a function or a way to generat it.
the way that i found now is to do it like that
<?php
$id_num = "SUD";
for ($i = 0; $i < 4; $i++) {
$id_num .= rand (0, 5);
}
echo $id_num;
?>
but this generates random number and iam not sure even it is unique or not any one
can help me please
you can do
$id = uniqid('SUD');
The trick here is recursion.
Steps:
Create a field with a UNIQUE constraint in the designated MySQL table.
Write a function 'generateCode' to generate a (long enough) code. *
Write a function that gets that code and tries to enter it in the database.
Fetch an eventual unique constraint violation and repeat the process from step 2 until it succeeds.
*) Be sure to use a code long enough to support your application for the coming years. 6 digits or a combination of alpha's and digits would most likely be enough.
Related
I want to generate a unique transaction code with using date an example: PSN-22102021-001 or PSN-22102021001, how to do it?
OK, not sure what database you are using, so will keep this in band.
I will assume the PSN is relevant to all codes, as you give no idea what this is.
Next, you will find generating unique IDs very difficult, and long, unless they are incremental in some way.
In PHP, you have two options (there are others, but I will let others fill those gaps). microtime(), or uniqid().
If you are using microtime(), you could use the following:
<?php
echo makeID();
function makeID($prefix = 'PRN'){
$time = str_replace('.', '-', microtime(true) );
return $prefix.'-'.$time;
}
This would return a number like: PRN-1634871496-0619
However, there is a very small possibility that two times are generated in the same microsecond, and this fails.
To ensure a unique ID, you would need to generate alpha-numeric options such as this..
<?php
echo makeUniqueId();
function makeUniqueId($prefix='PRN'){
return $prefix.'-'.uniqid();
}
This would return something like PRN-617229f798988
I need help to find workaround for getting over memory_limit. My limit is 128MB, from database I'm getting something about 80k rows, script stops at 66k. Thanks for help.
Code:
$posibilities = [];
foreach ($result as $item) {
$domainWord = str_replace("." . $item->tld, "", $item->address);
for ($i = 0; $i + 2 < strlen($domainWord); $i++) {
$tri = $domainWord[$i] . $domainWord[$i + 1] . $domainWord[$i + 2];
if (array_key_exists($tri, $possibilities)) {
$possibilities[$tri] += 1;
} else {
$possibilities[$tri] = 1;
}
}
}
Your bottleneck, given your algorithm, is most possibly not the database query, but the $possibilities array you're building.
If I read your code correctly, you get a list of domain names from the database. From each of the domain names you strip off the top-level-domain at the end first.
Then you walk character-by-character from left to right of the resulting string and collect triplets of the characters from that string, like this:
example.com => ['exa', 'xam', 'amp', 'mpl', 'ple']
You store those triplets in the keys of the array, which is nice idea, and you also count them, which doesn't have any effect on the memory consumption. However, my guess is that the sheer number of possible triplets, which is for 26 letters and 10 digits is 36^3 = 46656 possibilities each taking 3 bytes just for key inside array, don't know how many boilerplate code around it, take quite a lot from your memory limit.
Probably someone will tell you how PHP uses memory with its database cursors, I don't know it, but you can do one trick to profile your memory consumption.
Put the calls to memory-get-usage:
before and after each iteration, so you'll know how many memory was wasted on each cursor advancement,
before and after each addition to $possibilities.
And just print them right away. So you'll be able to run your code and see in real time what and how seriously uses your memory.
Also, try to unset the $item after each iteration. It may actually help.
Knowledge of specific database access library you are using to obtain $result iterator will help immensely.
Given the tiny (pretty useless) code snippet you've provided I want to provide you with a MySQL answer, but I'm not certain you're using MySQL?
But
- Optimise your table.
Use EXPLAIN to optimise your query. Rewrite your query to put as much of the logic in the query rather than in the PHP code.
edit: if you're using MySQL then prepend EXPLAIN before your SELECT keyword and the result will show you an explanation of actually how the query you give MySQL turns into results.
Do not use PHP strlen function as this is memory inefficient - instead you can compare by treating a string as a set of array values, thus:
for ($i = 0; !empty($domainWord[$i+2]); $i++) {
in your MySQL (if that's what you're using) then add a LIMIT clause that will break the query into 3 or 4 chunks, say of 25k rows per chunk, which will fit comfortably into your maximum operating capacity of 66k rows. Burki had this good idea.
At the end of each chunk clean all the strings and restart, set into a loop
$z = 0;
while ($z < 4){
///do grab of data from database. Preserve only your output
$z++;
}
But probably more important than any of these is provide enough details in your question!!
- What is the data you want to get?
- What are you storing your data in?
- What are the criteria for finding the data?
These answers will help people far more knowledgable than me to show you how to properly optimise your database.
So, I'm trying to make a gladiator game, where the players will be lanistas. I'm going for realism, so the gladiators will die in the arena, making a big influx of new "recruits" necessary.
For now, each newly created gladiator has 21 attributes, ranging from numerical values for things such as strength and agility, to text for faction and name. These are calculated by random functions. Names and factions I'm picking randomely from arrays with (at least for names) a relatively big list of realistic names. Numerical values are simply rand(x,y).
Before I added the name and faction arrays, I tried several times running the file that create gladiators with a while loop creating 10000 gladiators, without any clones emerging, as far as I could see. Now, with picking names too from random (as described above), everything works fine if I create a small number of gladiators, but once I use a number of a couple of hundred for my while loop, or if I run the file a few times in a row with as low a number as 50 in my while loop, I get clones.
With 21 attributes, 100 different values+ for most of them, getting clones doesn't happen by chance. Can anyone tell me what's wrong? This can kill my game, and I was just getting optimistic after overcoming a few (easy) challenges.
Oh, and yeah, the gladiators with the attributes are put into a mysql database automatically.
Edit (update):
I went back in my stuff, removed the naming and faction random functions, and set all to "s". Created 10000 gladiators named s s from faction s, and it seems there are excactly 0 clones - nobody with the exact same stats.
Reactivated the random name functions. Ran the file, creating 200 gladiators. Couldn't see clones. Ran it again. One clone for each gladiator. And again. Now two clones for the gladiators.
This random function isn't random at all, is it?
Edit (update 2):
Tested it again, with one of the previously excluded random functions activated one at a time. It seems its the firstname and surname functions that are screwing things up. Also, from my last test, it seems like there's a pattern, with gladiator id 209 being equal to 737, 77 being equal to 605 and 1133, 148 equal to 676, 772 equal to 244, and so on.
737-209, 605-77, 1133-605, 676-148, 772-244 all have one thing in comon. They all equal 528.
This isn't much random at all.
The function I use for getting names goes something like:
$surname=surname($faction) //surname is a function, using the variable $faction
function surname($faction) {
if ($faction=="Roman") {
$nomen = array("Aburius", "Accius", [...]);
$cognomen = array("Zeno", "Zonsimus", [...]);
$randnomen=array_rand($nomen,1);
$randcognomen=array_rand($cognomen,1);
$merge=array($nomen[$randnomen],$cognomen[$randcognomen]);
$surname=implode(" ",$merge);
return $surname;
}
To clarify: The [...] in the $nomen and $cognomen arrays is there in place of hundreds of roman names, to save space and your time.
array_rand seems to have a problem with randomness see here.
I prefer to use mt_rand myself.
The following function can create random names with either1,2 or three parts.
function randomName(){
$numargs = func_num_args();
$first = func_get_arg(0);
$one = count($first)-1;
$name = $first[mt_rand( 0,$one)]; //count($array)-1
if($numargs > 1){
$middle = func_get_arg(1);
$two = count($middle)-1;
$name .=" ". $middle[mt_rand( 0,$two)];
}
if($numargs > 2){
$last = func_get_arg(2);
$three = count($last)-1;
$name .= " ".$last[mt_rand( 0,$three)];
}
return $name;
}
USE
$var= randomName($first,$middle,$last);// 3 names
$var= randomName($first,$last);// 2 names
etc
WHERE $first,$middle,$last are arrays
With only ~100 values for an attribute and 1000s of gladiators, there may be many with the same name attribute, for example.
If you mean that there may be multiple gladiators where all 21 attributes are the same, then the only way to guard against that is to check newly created gladiators against the existing ones and if there is a match regenerate the new one.
Just like you would when someone registers for a site, normally username and email address must be unique per user, so you have to check first.
The easiest and most performant in this case might be to generate a "hash" of each gladiator's properties and check if it exists before generating a new gladiator. This will make them all unique, so you also need to consider how unique do you want them? Can 2 or more gladiators have 20 properties in common? How about 15, etc?
I am trying to create promo codes in large batches (with php/mysql).
Currently my code looks something like this:
$CurrentCodesInMyDB = "asdfasdf,asdfsdfx"; // this is a giant comma delimited string of the current promo codes in the database.
$PromoCodes = "";
for($i=0;$i<=30000;$i++)
{
$NewCode = GetNewCode($PromoCodes, $CurrentCodesInMyDB );
$PromoCodes .= $NewCode . ","; //this string gets used to allow them to download a txt file
//insert $newcode into database here
}
function GetNewCode($CurrentList, $ExistingList)
{
$NewPromo = GetRandomString();
if(strpos($CurrentList, $NewPromo) === false && strpos($ExistingList, $NewPromo) === false)
{
return $NewPromo;
}
else
{
return GetNewCode($CurrentList, $ExistingList);
}
}
function GetRandomString()
{
return "xc34cv87"; //some random 8 character alphanumeric string
}
When I do batches in 10k, it seems to be ok. But the client would like to be able to generate 30k at a time. When I bump the loop up to 30k, I've been having issues. Are there any obvious performance tweaks that I could make or maybe a different way I could do this?
You probably don't need to have all 30,000 codes loaded into memory in a single giant string. Just create a table in your database, add a code unique field (either primary key or unique index) and insert random codes until you have 30,000 successful insertions.
What kind of issues specifically?
My advice is: don't store the codes in a a CSV format, instead create a new indexed column and store each code on its own row - also, use prepared queries.
Doing 60,000 strpos() on a ~250 KB string might not be the best idea ever...
If you don't want to do inserts inside the loop.(they are also expensive) use an array and the method in_array to check for the string. Look in the comments for the in_array function there is someone saying that you can achieve better performance using array_flip and then checking for the array key
http://www.php.net/manual/en/function.in-array.php#96198
Hi guys I'm in a bit on a fix here. I know how easy it is to build simple pagination links for dynamic pages whereby you can navigate between partial sets of records from sql queries. However the situation I have is as below:
COnsider that I wish to paginate between records listed in a flat file - I have no problem with the retrieval and even the pagination assuming that the flat file is a csv file with the first field as an id and new reocrds on new lines.
However I need to make a pagination system which paginates backwards i.e I want the LAST entry in the file to appear as the first as so forth. Since I don't have the power of sql to help me here I'm kinda stuck - all I have is a fixed sequence which needs to be paginated, also note that the id mentioned as first field is not necessarily numeric so forget about sorting by numerics here.
I basically need a way to loop through the file but backwards and paginate it as such.
How can I do that - I'm working in php - I just need the code to loop through and paginate i.e how to tell which is the offset and which is the current page etc.
I'm assuming you have a well-formed document with delimiters.
$array = explode("<>", $source); //parse data into an array
$backward = array_reverse($array); //entire array is reversed - last elements are now first
Use this code for a jumping off point.
$records = file('filedata.csv');
$recordsInOrder = array_reverse($records);
$first = 5;
$last = 10;
for($x = $first; $x <= $last; $x++) {
$viewTheseResults[] = $recordsInOrder[$x];
}
You can use an offset to determine the starting and ending keys in the array similar to how you would if you were pulling the data from a database.