Home > front end >  How to randomly retrieve data from the database
How to randomly retrieve data from the database

Time:01-16

I'm not very good at English but I'll try to make myself understood.

In a nutshell, I'm trying to randomly retrieve data from the database, and so far no problem. The problem is that the answer is given to me like this: {"pda": 15} {"pda": 34} {"pda": 776} {"pda": 344} {"pda": 16}, while I would like it to be replied like this: {"pda": 15,34,776,344,16}.

Could you tell me a solution?

The code is this:

    $stmtcarte = $connection->prepare("SELECT pda FROM giocatori WHERE categoria=? ORDER 
    BY RAND() LIMIT 6");
    
    //imposto categorie da selezionare
    //imposto probabilità di scelta della categoria
    $sceltacategoria = array(
    'nor'        => 85,
    'sop'       => 9,
    'buo' => 5,
    'cos' => 1,
    );
    $max = 0;
        
    foreach ($sceltacategoria as $categoriaselezionata => $weight)
    {
    $max           = $weight;
    $sceltacategoria[$categoriaselezionata]  = $max;
    }
    $random = mt_rand(1, $max);
    
    foreach ($sceltacategoria as $categoriaselezionata => $max)
    {
    if ($random <= $max)
    {
    break;
    }
    }
    
    $categoria=$categoriaselezionata;
    $stmtcarte->bind_param("s",$categoria);
    $stmtcarte->execute();
    $risultatocarte = $stmtcarte->get_result();
    //numero giocatori estratti
    $numero_giocatori = $risultatocarte->num_rows;
    while($rispostacarte=$risultatocarte->fetch_assoc()){
          echo json_encode($rispostacarte);
    }
    $stmtcarte->close();

CodePudding user response:

Use GROUP_CONCAT

$connection->prepare("

SELECT
    GROUP_CONCAT(concat.pda) as pda
FROM (
    SELECT pda
    FROM giocatori
    WHERE categoria=?
    ORDER BY RAND()
    LIMIT 6
) concat

");

This requires you to first randomly order the items and limit them, and then in a separate query do the GROUP_CONCAT. Otherwise, like you mentioned in your comment, the LIMIT doesn't work as expected because only 1 row is returned.

Working demo at http://sqlfiddle.com/#!9/14c35a/3

  •  Tags:  
  • Related