Hello.
There was a task - to extract a pseudo-ordinal record from the database, however, its ID should not fall into the range of available ones (for example, those used earlier).
The result is such an "algorithm".
$ids = explode(',',$_SESSION['vars']); if (count($ids) == 4){ $_SESSION['vars'] = '0'; die(); } $get = $this->db->query("SELECT COUNT(*) AS `count` FROM `quests`"); $get = $get->fetch(PDO::FETCH_ASSOC); $cnt = $get['count']; while(!$flag){ $rnd = rand(1,$cnt); if (in_array($rnd,$ids)){ $flag = false; echo 'Элемент с ID '.$rnd.' существует! <br>'; }else{ $flag = true; } } $get = $this->db->query("SELECT * FROM `quests` WHERE `id` = ".$rnd); $get = $get->fetch(PDO::FETCH_ASSOC); $vars.=','.$rnd; $_SESSION['vars'] = $vars; `The question is: is it possible to implement this as using only SQL?
select * from quests where id not in(1,5,10,76) order by rand() limit 1will give the desired result in principle, but is this optimal in your case - Mikenot incan be a problem. Andorder by rand()will read the entire table. Fetching a specific record by a previously known ID is an order of magnitude faster. True, your current code requires that all IDs be strictly in the table from 1 to the number of records - Mikenot inwill be no more than 14 ID. There are a couple of hundred entries in the table. And how is it limited? What does he require? If the count of records in the table is initially extracted, and on the basis of it, a random number is generated as a limit. I missed something, apparently? - Vitaliy RS