I want to create some random sql data with a php script
currently I get the last record, generate a random number between 1 and 2 ... if its a 1 I will add a random number to the record else if its a 2 i will subtract a random number from
the problem is it keeps spitting out minus random numbers! I only want positive random numbers.
$result = mysql_query("SELECT * FROM Data ORDER BY id DESC")
or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
$temp=$row['temp'];
$light=$row['light'];
};
$name="Herbi";
$date=Date("o:m:d");
$time=Date("H:i:s");
$rand =rand(1,2);
$randnu =rand(1,10);
echo " rand:".$rand;
switch($rand){
case 1:
$temprand=$temp+$randnu;
$lightrand=$light+$randnu;
break;
case 2:
$temprand=$temp-$randnu;
$lightrand=$light-$randnu;
break;
};
echo"";
echo"randnu";
echo $randnu;
echo " ";
echo"lightrand";
echo $lightrand;
Based on your code this is valid, if your $temp=1 and $rand=2 then $temprand will be -1.
You can add a check that your $temp and $light should always be greater than or equal the max random numbers so when you minus the (max of) random number from $temp or $light you will end up with 0.
if($row['temp']>=2){
$temp=$row['temp'];
}else{
$temp=2; //Max of $rand =rand(1,2);
}
or shorthand
$temp=($row['temp'] >= 2? $row['temp'] : 2);
$light=($row['light'] >= 10? $row['light'] : 10);
Related
Consider $number="1234567890";
How can I get the result as "gRkBDa7890"
The first 6 digits should be replaced with random upper and lower case letters and only last 4 digits of $number should be the same. The value to $number will be different each time but always it will 10 digit number. The purpose is to generate referral/invite code for each user from their phone number.
you can try this
$number = "1122334455667788";
$masked = str_pad(substr($number, -4), strlen($number), ' ', STR_PAD_LEFT);
function generateRandomString($length = 10) {
return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
}
$genco = generateRandomString();
$reffcode = $genco.$masked;
$reffcode = str_replace(' ', '', $reffcode);
echo trim($reffcode);
and for not repeating you should add all given referral code in the database
an then you when you give new reff code to other then need to check
that it is already registered or not
if true then regenrate string
if false then give the generated string
The trick is to first seperate the 4 last digits from the phone number, then create a new 6 character long random string of lowercase and uppercase letters. Next, you combine the two.
As Glossy Power said, you should check the newly created referral code against the exists codes in your database. This is done in a while loop form. The code below will does this.
function referral_code($phone_number){
// Get last four digits from phone number
$last_four_digits = substr($phone_number, -4);
// Set continue to true for looping
$continue = true;
// Loop
while ($continue) {
// Accepted characters for first part of referral link
$input = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Initiate variable
$random_letters = '';
// Create 6 character random string
for ($i = 0; $i < 6; $i++) {
$random_letters .= $input[rand(0, strlen($input) - 1)];
}
// Combine new random string with last four digits
$referral_code = $random_letters.$last_four_digits;
// Check if the newly created referral code is present in database
$sql = "SELECT referral_code FROM table WHERE referral_code = '$referral_code' LIMIT 1";
$result = mysqli_query($connection, $sql);
// If number of returned rows is zero
if(mysqli_num_rows($result) == 0) {
// Set continue to false to stop loop
$continue = false;
// Return referral code
return $referral_code;
}
}
}
You can initiate the function like so:
echo referral_code('0612345678');
This will return a 10 character string where the first 6 characters are random lowercase and uppercase letters and the last 4 characters are 5678.
I did some research, but didn't found any solution for my question.
What I want to archive:
Generate a random number out of 0's ($min) and 1's ($max), but with a fixed amount ($many) of 1's in the random number. The random number should have a length of 6 as in my while loop (while($xLoop <= 6)).
Here is my current code:
$min = 0;
$max = 1;
$many = 3;
$xLoop = 1;
while($xLoop <= 6) {
$nRand = mt_rand($min,$max);
if($nRand == 1){ //if random number comes out number 1
$many--; // Prevent number 1 more then $many...
//Do something...
}else{ //if random number comes out not number 1
//Do something and still looping until get 6 times
}
echo $nRand.' - '.$many.'</br>'; //For debugin... i want to see how many number 1 comes out.
$xLoop++;
}
It will loop 6 times, so we have a random number of the length 6, but I want a fixed amount of 1's in my random number, which is $many (here 3). And the rest filled with 0's until we reach the length 6.
How can I fix this code? Or is there a simpler way?
This should work for you:
No need for a loop. Just first fill an array with 1's $many times. Then array_merge() the array with the 0's which you fill up until $length elements.
At the end just shuffle() the array and implode() it to print it
<?php
$min = 0;
$max = 1;
$many = 3;
$length = 6;
$arr = array_fill(0, $many, $min);
$arr = array_merge($arr, array_fill($many, $length-$many, $max));
shuffle($arr);
echo implode("", $arr);
?>
possible output:
011010
I'm trying to assign a different random number on each item in a foreach loop but I'd like the number to stay the same for one day.
I've tried simply adding <?php echo rand(0,20); ?> but this obviously just creates a random number per each refresh.
Is there anyway I could keep the same random number per each item for one day without adding it to the database.
for example:
item 1 = 2
item 2 = 18
item 3 = 13
item 4 = 6
Stays the same for 1 day then changes
You can do this by programming your own random number generator. This guide shows you how to do it.
Note: Code below from sitepoint
class Random {
// random seed
private static $RSeed = 0;
// set seed
public static function seed($s = 0) {
self::$RSeed = abs(intval($s)) % 9999999 + 1;
self::num();
}
// generate random number
public static function num($min = 0, $max = 9999999) {
if (self::$RSeed == 0) self::seed(mt_rand());
self::$RSeed = (self::$RSeed * 125) % 2796203;
return self::$RSeed % ($max - $min + 1) + $min;
}
}
To call it
// set seed
Random::seed(42);
// echo 10 numbers between 1 and 100
for ($i = 0; $i < 10; $i++) {
echo Random::num(1, 100) . '<br />';
}
Now set your seed based on the current date with the php date function
// set seed based on date with
Random::seed(date("z") + 1);
This will give you the same numbers every year. If you don't want this, use the seed variable of rubo77. With this version you can ensure to get the same number on different machines (can't guarantee that with srand).
Maybe you could try something like:
$not_random_at_all = base_convert(md5($item . date('l jS \of F Y')), 16, 10);
Where $item is the number of your item (or anything that identifies the item).
It just converts the MD5-Hash of the current date concatenated with your item number to integer.
That means a different random number for every item daily.
Remember that MD5 is not a random number generator and your results might bot be as random as they can be.
$seed = floor(time()/86400);
srand($seed);
foreach($list as $item){
echo $item.rand(0,20);
}
or to obtain the same value of rand in a determined time interval.
Another Example: you have an array of 20 elements and you need to obtain a random item every day but not to change in the 24h period (just imagine "Today's Photo" or similar).
$seed = floor(time()/86400);
srand($seed);
$item = $examplearray[rand(0,19)];
You obtain the same value every time you load the page all the 24h period.
in mock test, i store id of questions in an array and i want when test start then it generate radomly id's from this array. when id is less then 10 then it generate correct number but when it store greater then 10 like 20,21,22.. then it also generate also number form 1-10. i want it generate random number from number which store in this array. thnax..
$ids= array('20','21','22','23','24','25','26','27','28','29','30','31','32',);
$getIds=mysql_query("select * from mock_test_question where status='1' and question_level='FINAL' ") or die(mysql_error());
while($data=mysql_fetch_array($getIds))
{
array_push($ids, $data['id']);
}
print_r($ids);
echo "</br>";
$rand_keys = array_rand($ids,5);
$_SESSION['quesid']=$rand_keys;
print_r($rand_keys);
array_rand returns the KEYS (array positions) not the actual values. To get the values:
echo $ids[$rand_keys];
This should give you a random number
$randomValues = array('20','21','22','23','24','25','26','27','28','29','30','31','32');
$randomValuesIndex = array_rand($randomValues, 1);
$randomValue = $randomValues[$randomValuesIndex];
echo $randomValue."\n";
An example loop that generates random numbers
$randomValues = array('20','21','22','23','24','25','26','27','28','29','30','31','32');
for ($i = 1; $i < 30; $i++)
{
$randomValuesIndex = array_rand($randomValues, 1);
$randomValue = $randomValues[$randomValuesIndex];
echo $randomValue."\n";
}
$count = count($ids) - 1; # note that its -1 because array keys start from 0
echo $ids[rand(0,$count)];
here is a fast way to get random element from array
P.S>
Here is complete code with generate of numbers and usage..
$ids = array();
for($i=20;$i<=32;$i++){ $ids[]=$i; }
$count = count($ids) - 1;
echo $ids[rand(0,$count)];
echo $ids[rand(0,$count)];
echo $ids[rand(0,$count)];
I have system in PHP in which I have to insert a Number which has to like
PO_ACC_00001,PO_ACC_00002,PO_ACC_00003.PO_ACC_00004 and so on
this will be inserted in Database for further reference also "PO and ACC" are dynamic prefix they could different as per requirement
Now my main concern is how can is increment the series 00001 and mantain the 5 digit series in the number?
>> $a = "PO_ACC_00001";
>> echo ++$a;
'PO_ACC_00002'
You can get the number from the string with a simple regex, then you have a simple integer.
After incrementing the number, you can easily format it with something like
$cucc=sprintf('PO_ACC_%05d', $number);
Create a helper function and a bit or error checking.
/**
* Takes in parameter of format PO_ACC_XXXXX (where XXXXX is a 5
* digit integer) and increment it by one
* #param string $po
* #return string
*/
function increment($po)
{
if (strlen($po) != 12 || substr($po, 0, 7) != 'PO_ACC_')
return 'Incorrect format error: ' . $po;
$num = substr($po, -5);
// strip leading zero
$num = ltrim($num,'0');
if (!is_numeric($num))
return 'Incorrect format error. Last 5 digits need to be an integer: ' . $po;
return ++$po;
}
echo increment('PO_ACC_00999');
Sprintf is very useful in situations like this, so I'd recommend reading more about it in the documentation.
<?php
$num_of_ids = 10000; //Number of "ids" to generate.
$i = 0; //Loop counter.
$n = 0; //"id" number piece.
$l = "PO_ACC_"; //"id" letter piece.
while ($i <= $num_of_ids) {
$id = $l . sprintf("%05d", $n); //Create "id". Sprintf pads the number to make it 4 digits.
echo $id . "<br>"; //Print out the id.
$i++; $n++; //Letters can be incremented the same as numbers.
}
?>