randomly generate for a period of time in php

Asked

Viewed 227 times

0

I have this code:

<?php 

$array_number = array();
for($i = 1; $i <=11; $i++)
{
    $value = rand(1,11);
    while (in_array($value, $array_number))
    {
        $value = rand(1,11);
    }
    $array_number[$i - 1] = $value;
}

$servername = "xxx.xxx.x.xx";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxxcxx";

$conexao = new mysqli($servername, $username, $password, $dbname); //Conecta com o banco de dados
$conexao->set_charset('utf8');

$id = $array_number[1]; //Joga o primeiro valor sorteado para a variável $id
$instrucao = mysqli_query($conexao, "SELECT NomeColaborador FROM centrodb.InfoColaboradores WHERE Id = '$id' "); //Cria uma instrução de busca pelo $id no seu banco de dados
$consulta = mysqli_fetch_assoc($instrucao); //Executa a primeira instrução
echo "Ala A Grupo 1 - Turno_M - " . $consulta['NomeColaborador'] . "<br/>"; //Imprime

$id = $array_number[2]; //Atualiza a $id para o segundo numero sorteado
$instrucao = mysqli_query($conexao, "SELECT * FROM centrodb.InfoColaboradores WHERE Id = '$id' "); // Atualiza a instrução para a nova $id
$consulta = mysqli_fetch_assoc($instrucao); //Executa instrução da nova busca pelo 2º $id
echo "Ala A Grupo 2 - Turno_M - " . $consulta['NomeColaborador'] . "<br/>"; //Imprime

$id = $array_number[3]; //Atualiza a $id para o terceiro numero sorteado
$instrucao = mysqli_query($conexao, "SELECT * FROM centrodb.InfoColaboradores WHERE Id = '$id'"); // Atualiza a instrução para a nova $id
$consulta = mysqli_fetch_assoc($instrucao); //Executa instrução da nova busca pelo 3º $id
echo "Ala A Grupo 3 - Turno_M - " . $consulta['NomeColaborador'] . "<br/>"; //Imprime

$id = $array_number[4]; //Joga o primeiro valor sorteado para a variável $id
$instrucao = mysqli_query($conexao, "SELECT NomeColaborador FROM centrodb.InfoColaboradores WHERE Id = '$id' "); //Cria uma instrução de busca pelo $id no seu banco de dados
$consulta = mysqli_fetch_assoc($instrucao); //Executa a primeira instrução
echo "Ala B Grupo 1 - Turno_M - " . $consulta['NomeColaborador'] . "<br/>"; //Imprime

$id = $array_number[5]; //Atualiza a $id para o segundo numero sorteado
$instrucao = mysqli_query($conexao, "SELECT * FROM centrodb.InfoColaboradores WHERE Id = '$id' "); // Atualiza a instrução para a nova $id
$consulta = mysqli_fetch_assoc($instrucao); //Executa instrução da nova busca pelo 2º $id
echo "Ala B Grupo 2 - Turno_M - " . $consulta['NomeColaborador'] . "<br/>"; //Imprime

$id = $array_number[6]; //Atualiza a $id para o terceiro numero sorteado
$instrucao = mysqli_query($conexao, "SELECT * FROM centrodb.InfoColaboradores WHERE Id = '$id'"); // Atualiza a instrução para a nova $id
$consulta = mysqli_fetch_assoc($instrucao); //Executa instrução da nova busca pelo 3º $id
echo "Ala B Grupo 3 - Turno_M - " . $consulta['NomeColaborador'] . "<br/>"; //Imprime

$id = $array_number[7]; //Atualiza a $id para o segundo numero sorteado
$instrucao = mysqli_query($conexao, "SELECT * FROM centrodb.InfoColaboradores WHERE Id = '$id' "); // Atualiza a instrução para a nova $id
$consulta = mysqli_fetch_assoc($instrucao); //Executa instrução da nova busca pelo 2º $id
echo "Responsável de Turno- Turno_M - " . $consulta['NomeColaborador'] . "<br/>"; //Imprime

$id = $array_number[8]; //Atualiza a $id para o terceiro numero sorteado
$instrucao = mysqli_query($conexao, "SELECT * FROM centrodb.InfoColaboradores WHERE Id = '$id'"); // Atualiza a instrução para a nova $id
$consulta = mysqli_fetch_assoc($instrucao); //Executa instrução da nova busca pelo 3º $id
echo "Apoio - Turno_M - " . $consulta['NomeColaborador'] . "<br/>"; //Imprime

?>
</div>

This code returns this:

[![insert image description here][1][1]

But I want to create a form like this:

<form method="POST" action="">
	<strong>Pesquisar:</strong><input type="Date" name="inicio" placeholder="PESQUISAR">
	<strong>Pesquisar:</strong><input type="Date" name="fim" placeholder="PESQUISAR">
	<input type="submit" name="pesquisa" value="ENVIAR">
</form>

Where I put a period of time and he manages me a table with a result like this:

  • And what does this code do? What should I do and what should I not do?

  • It has to be by PHP ? Because to be automatic, it would be by Javascript I believe.

  • It doesn’t have to be by php, it was the way I got it, you can put an example to generate this process for a period of time?

  • Bruno, your question is unclear. If you want to redeem the values of the database by randomizing the results the right one was to do this with only one querie using ORDER BY RAND(), then create a routine with ajax to keep requesting this page in the backend and exchanging the returned values. Explain better to have answers that help.

  • Rafael, I intend this, but I have 4 shifts, the morning shift with 11 employees and I just want you to call 8, afternoon shift with 5 employees and call 4, afternoon shift 2 with 4 collaborators and call 3 and night shift with 4 collaborators and call 2. I intend that he manages it randomly in a time interval chosen by me and if the employee is off one of those days he is excluded from random assignment.

3 answers

-1

How about scheduling the PHP script on Cron? Behold here how to do this.

-1

Use the javascript method "setTimeOut()".

You create a javascript function and pass it as a parameter of this method, as well as the number of seconds that this function should be executed, and within this function you put the logic you want; example:

<html>
<head>
<script type="text/javascript">
var timer=0;
function startTimer()
{
setInterval("timerUp()",1000);
}

function timerUp()
{
timer++;
    var resetat=180; //tempo em segundos
if(timer==resetat)
{
	window.location.reload();
}
var tleft=resetat-timer;
document.getElementById('timer').innerHTML=tleft;
}

</script>
</head>
<body onload="startTimer()">
Seconds until page reloads:
<div id="timer">
</div>
</body>
</html>

  • But I intend to generate me this result randomly for 15 days for example, assign 8 employees of the 11 for each day, randomly

  • you put -1 because you want me to do it for you ?

  • I didn’t put -1 in any of the solutions that I was given..... someone did, but I didn’t.... I appreciate all your help. I’ve been testing your example, and it works in seconds, it’s always generating a new one, but I intended it in a period of time of days, and then show the generated employees on a schedule for each day, with the generated employees on that day.

-1

You can use a key derivation, with a key and the current date (the current week, the current month or the current time), so you will always have the same result with the same key input and the same date.

Can also, instead of doing all this, simply store the data in a file, for a time determined by you. Then generate only once and then take the saved data while there is no need to generate new ones.

But I will consider that you do not wish to store the information.


I will go into much more technical details, there are other publications on Stackoverflow and Cryptography (from Stackexchange) deal with the subject.

Suppose you have to generate a new set per week. For example, in the current week (01/18/2018) you have A,B,C. The following week, starting on Monday, 01/22/2018, you have C,B,A.

So you use exactly the code:

$data = date('Y-W');

This will return the year (Y) and the week of the year (W), today he is 2018-03, tomorrow will also be, but on 22/01 will be 2018-04, on 30/01 will be 2018-05...


Now you know how to generate a unique number per week, although it is guessable. We cannot use it to generate random data directly, for an obvious reason.

So we use a KDF, like HMAC, HDKF or PBKDF, in case I will use HMAC, because it is enough.

$chave = "DEFINA-AQUI-UMA-CHAVE-SECRETA";
$data = date('Y-W');
$aleatorio = hash_hmac('sha512', $data, $chave, true);

So now we can select the necessary numbers. Therefore, we have to limit to 1 up to 11, this can be possible using 4 bit and decanting what is not useful.

$aleatorio = hash_hmac('sha512', $data . '-' . ++$g, $chave, true);
$aleatorio =  unpack('J*', $aleatorio);


foreach($aleatorio as $n){
    $i = 0;

    while($i < 16){
        $n4bits = $n & 15;
        $n >>= 4;
        $i++;

        if($n4bits >= 1 && $n4bits <= 11 && in_array($n4bits, $random_number) === false){
            $random_number[] = $n4bits;
        }
    }   
}

This will be able to generate numbers between 1 and 11 in a alentary way, fixed for a week based on the key. Soon, someone who knows the current week and does not know the key will not be able to predict future combinations.


Finally, we will have the following thing:

$chave = "DEFINA-AQUI-UMA-CHAVE-SECRETA";
$data = date('Y-W');
$array_number = [];


$g = 0;
criarnovahash:
$aleatorio = hash_hmac('sha512', $data . '-' . ++$g, $chave, true);
$aleatorio =  unpack('J*', $aleatorio);


foreach($aleatorio as $n){
    $i = 0;

    while($i < 16){
        $n4bits = $n & 15;
        $n >>= 4;
        $i++;

        if($n4bits >= 1 && $n4bits <= 11 && in_array($n4bits, $array_number) === false){
            $array_number[] = $n4bits;
        }
    }   
}


if(count($array_number) !== 11){
    goto criarnovahash;
}

Use this above instead of:

$array_number = array();
for($i = 1; $i <=11; $i++)
{
    $value = rand(1,11);
    while (in_array($value, $array_number))
    {
        $value = rand(1,11);
    }
    $array_number[$i - 1] = $value;
}

The effect will be "the same", with the difference being fixed by each week, for example.


An example today (week 2018-03) and with a key pack('H*', '114b3ff54571da742ae58399eb0b7aa7acb68703b3b7325b4f4dc933aad0e9dd'), would be:

array(11) {
  [0]=>
  int(4)
  [1]=>
  int(1)
  [2]=>
  int(5)
  [3]=>
  int(8)
  [4]=>
  int(7)
  [5]=>
  int(9)
  [6]=>
  int(10)
  [7]=>
  int(3)
  [8]=>
  int(6)
  [9]=>
  int(2)
  [10]=>
  int(11)
}

The following week (2018-04) would be:

array(11) {
  [0]=>
  int(7)
  [1]=>
  int(4)
  [2]=>
  int(1)
  [3]=>
  int(5)
  [4]=>
  int(10)
  [5]=>
  int(6)
  [6]=>
  int(2)
  [7]=>
  int(8)
  [8]=>
  int(11)
  [9]=>
  int(3)
  [10]=>
  int(9)
}

  • 1

    I wanted to know why from -1, this solves the problem that the OP wants. In my view, since it will always have the same results "a period of time", it can be chosen arbitrarily the period.

  • I’m sure the -1 was because neither read and did not understand.

  • I didn’t put the -1.... I don’t understand why the -1 is appearing in the three aids I received

  • I’m not able to put into practice the idea you gave me, can you give me any more hints? As I add what you had to the scheme you presented me?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.