Generating random ref_id in PHP?

one text

i want to create different ref_id for each users. i tried it with using str_shuffle function. it generates but when i refresh the page it changes. also, it generates the same ref_id for every user. Here are my codes:**

$users = $db->get_results("SELECT * FROM users");
if($users ){
  foreach($users as $u){
    $str = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPUQRSTUVWXYZ';
    $str_r = substr(str_shuffle($str), 0, 30);
    $ref_id=$db->query("UPDATE users SET ref_id= '$str_r'") ;
    echo "ref_id: $u->ref_id; ";
    echo '<br';
  }
}

i think i must use while but i didnt get any result. How can i fix this?**

Edit: i solved the part of "generating different id for each users" but still changes every refreshing. How can i solve that part?

here are the new version of codes above:

$users = $db->get_results("SELECT * FROM users");
if($users){
  echo '<div class="container">
         <div class="card">
           <div class="card-body">';
    foreach($users as $u){
      $str = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPUQRSTUVWXYZ';
      $str_r = substr(str_shuffle($str), 0, 20);
      $ref_id=$db->query("UPDATE users SET ref_id= '$str_r' where id='$u->id'") ;
       echo "$u->id . users ref_id: $u->ref_id; ";
       echo '<br>';

      }
    }

  echo '</div></div></div>';

Source