doufei7464 2018-05-09 10:16 采纳率: 0%
浏览 16
已采纳

从DB中挑选一个随机名称而不重复,直到使用所有名称

Hey there StackOverflow community as the title says , I have a table in my DB with 2 columns ID and Name. there is a html form with a button, by clicking the button I want it to pick a name. by clicking again , it picks a name without repeat until all names are used.

Here's what I've done so far:

<?php 
include ("config.php");
$result = '';

if (isset($_POST['rand'])) {
    $name_query = mysqli_query($conn,"SELECT * FROM names ORDER BY RAND() LIMIT 1");
    $name_f = mysqli_fetch_assoc($name_query);
    $result = $name_f['name'];
}
 ?>

 <form action="" method="post" accept-charset="utf-8">
    <input type="submit" name="rand">
 </form>

<div><?php echo $result;?></div>

thanks in advance.

  • 写回答

1条回答 默认 最新

  • duangang79177 2018-05-09 12:55
    关注

    I think the right way to do that is creating a text file and save names in it whenever you fetch for the latter in the database. Then for subsequent fetching, check whether the name exists in the file content or not.

    $result = '';
    
    function getName(){
       $file_path = "file.txt";
       $where = "";
       if(file_exists($file_path)){
           $lines = file($file_path);
           if(count($lines) > 0){
              $where = " WHERE `name` NOT IN(".implode(',', $lines).") ";
           }
       }
       $name_query = mysqli_query($conn,"SELECT * FROM `names` $where ORDER BY RAND() LIMIT 1");
       if(mysqli_num_rows($name_query) > 0){
           $name_f = mysqli_fetch_assoc($name_query);
           $result = $name_f['name'];
           file_put_contents($file_path, $result.PHP_EOL , FILE_APPEND | LOCK_EX);
           return $result;
       }else{
          file_put_contents($file_path, "");
          return getName();
       }
    }
    
    if(isset($_POST['rand'])) {
       $result = getName();
    }
    
    
    <form action="" method="post" accept-charset="utf-8">
        <input type="submit" name="rand">
     </form>
    
    <div><?php echo $result;?></div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大