Generate a query number?

Asked

Viewed 117 times

-5

I have a search system and I want to generate a number for each search made in the database, I’m thinking of using the rand to generate the numbers, then take the generated number and save to the database.

It would be a good idea to use function rand for that reason?

Example:

include_once('conexao.php');

$nome = $_GET('nome');

$n = rand(0, 100000);

$cons = "INSERT INTO nconsulta (n1consultan, nome) VALUES '$n', 'nome'";
$executar = mysqli_query($conexao, $cons);
  • It could better detail what the "number for each query" would be and describe why it needs it and how it will be used?

  • @Andersoncarloswoss updated the question

  • 3

    Any specific need for random number? Wouldn’t an id with auto increment be better? For, however small the chance, certainly one hour the Rand will give a repeated number. In order not to take that risk, you would first need to consult if Rand does not exist in the bank and then record.

3 answers

5

You tagged that question with the tags and . Although I didn’t use the , I see in your example code you’re calling mysqli, then I hope you are using some version of Mysql. If you are wrong, please tell us.

Not enough information has been provided to "guess" how you are tracking these searches. Or what your intention is with them. If you want to track each search individually (for example, generate a chronological log) I suggest you record this in a dedicated table and use a primary key id with the guy AUTO_INCREMENT. Perhaps it is also interesting one or two fields that store the timestamp of the query, so that you can have chronological traceability and not just numerical.

Maintain a column id of the kind AUTO_INCREMENT in primary key is a joker to solve most of the relational logics you may have. Allows you to search for older, newer ones, sort, group, or filter with ease. If you have date fields as auxiliaries, higher granularity still.

CREATE TABLE query_log (
     id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
     query_string TEXT NOT NULL,
     created_at DATETIME NOT NULL,
     updated_at DATETIME NOT NULL
   );

INSERT INTO query_log (query_string, created_at, updated_at)
    VALUES("frango frito", NOW(), NOW());

If you wish, however, store queries unique to your search system (ex: want to know you searched "fried chicken", but do not want an input for each query) you can still use the same field id with AUTO_INCREMENT as I mentioned, just check if the query text already exists before saving.

Using your "example":

include_once('conexao.php');

$nome = $_GET('nome');      // Isso aqui deveria ser a "frase" da consulta???
// $n = rand(0, 100000);    // Não precisamos mais "gerar" o ID

$cons = "INSERT INTO query_log (query_string, created_at, updated_at) VALUES ('$nome', '2018-11-07 11:21:00', '2018-11-07 11:21:00')";
$executar = mysqli_query($conexao, $cons);

As you would like to deal with dates (in case of dealing with dates), it is up to you. You can manually write the functions that suit you best or if you want a library that provides this type of help you can try the Carbon.

The truth is that, without more specific information, any answer will be speculative and its accuracy will be as subjective as the question itself. There are numerous ways to implement what you have written, right or wrong depends on what you want; which is exactly what is unclear.

You could generate a hash of the query, encrypt the results and make a XOR then invert the bits and have a server sign to verify the authenticity and then return to your backend. Do you need to do this? Most likely nay. But only you can tell us.

I sincerely believe that in this case using date literals or UID functions are Overkill, unnecessary or will bring other problems in the future.

By the way, when it comes to PHP, one of the problems of PHP code demonstrated above is the ease of a bad person to inject code into your database and cause all kinds of problems. There are native functions to prepare your query and as far as possible avoid a malicious code injection through your system.

I suggest you read on official PHP documentation about Mysqli before proceeding with your project.

0

You can take the current time and multiply it with some random value, or even your bank’s last id.

    $id=10;
    $data = date('Y/m/d H:i:s');
    $x = $id*strtotime($data);
  • 2

    This will burst easy numerical storage capacity.

  • True, but the idea was to avoid multiple access at the same time. It could add with the id then.

  • I could do something mixed, like take strtotime * 1000 + ( id % 1000 ), but then I would have to adjust it to his case (this 1000 would be assuming that there will not be 1000 inserts in the same second, but I would have to guarantee this) - one thing that would help would be to "shorten" strtotime() taking about 40 years (would be from 2010 forward only) - but in the future would need to revise to not burst integer (in 64 bits would have no problem)

0

I believe that if you can better explain your need for random number someone can show you a better way.

At first, if there is no reason for this number to be random, Mysql relies on the "auto-incrementable" field, which will generate a different number for each line. (See more here.)

If this does not meet your need, you can develop a logic to generate a random ID, based on the current time among other things. Something like this here:

$uid = hexdec(uniqid());
// exemplo de saída: 1616475946956388

Recalling that the uniqid returns numbers in their hexadecimal representation, so its conversion is required to have only numbers, as in the above code.

You can also add the current date (Unix) to make it even more unique:

$uid = time() . '' . hexdec(uniqid());
// exemplo de saída: 15415914151616475760156156

So you don’t need to make a query in the bank before inserting a line to check if the ID already exists.

  • 2

    If you’re going to use numeric, you don’t have to use uniqid, you better take pure time (which is where uniqid takes hexadecimal, after all). However, only time can give a race condition problem if 2 inserts occur in the same second

  • Exactly. That’s why I find it more interesting to use both to considerably decrease the risk of conflict. Although uniqid uses time, the output is not the same.

Browser other questions tagged

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