3

I want to be able to select a STUDENT randomly who has not FACED the exam ('N') and echo the name and subject. How can I achieve this?

$query = $db->prepare('SELECT name FROM exams WHERE faced = ?');
$array = array('N');
$query->execute($array);

enter image description here

Dharman
  • 30,962
  • 25
  • 85
  • 135
NathaliaZeed
  • 139
  • 4
  • 11

1 Answers1

8

You can use something like:

$query = $db->prepare('SELECT name, subject
          FROM exams WHERE faced = ?
          ORDER BY RAND() LIMIT 1');
$array = array('N');
$query->execute($array);

$result = $query->fetchAll(PDO::FETCH_COLUMN, 0);

var_dump($result);
Rick James
  • 135,179
  • 13
  • 127
  • 222
ajtrichards
  • 29,723
  • 13
  • 94
  • 101
  • 1
    Just for the future: http://www.webtrenches.com/post.cfm/avoid-rand-in-mysql Try to avoid using this method, and maybe try something from the following post: http://stackoverflow.com/questions/4329396/mysql-select-10-random-rows-from-600k-rows-fast – Michael Arenzon Feb 18 '14 at 12:49
  • 1
    Yes RAND() is a recipe for killing mysql server !! – Abhik Chakraborty Feb 18 '14 at 12:50
  • If you have `INDEX(faced)` it won't be so bad. Even better would be a "covering" `INDEX(faced, name, subject)`. – Rick James May 07 '18 at 21:37