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.
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>