Q:

array_rand function returns empty sometimes

I want to make a little service.The service's main idea is to show one record from mysql table and it makes this per click at randomly.
Here is the code that i wrote:
<?php
require'connection.php';

$dbQueryFirst = $nesnePDO->prepare("SELECT CategoryID FROM Categories");
$dbQueryFirst->execute();   
while ($resultsFirst = $dbQueryFirst->fetch(PDO::FETCH_ASSOC)) 
{
    $getidFirst[] = $resultsFirst;
    $puppet = array_rand($getidFirst);
    if ($puppet == null && empty($puppet)) 
    {
        shuffle($getidFirst);       
    }       
}

$rndID = $puppet;

$dbQuerySecond = $nesnePDO->prepare("SELECT * FROM Categories WHERE CategoryID = :CategoryID");
$dbQuerySecond->bindParam(":CategoryID",$rndID);
$dbQuerySecond->execute();
$resultsSecond = $dbQuerySecond->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($resultsSecond);
?>

First query is,get id's from db and take them into array.Second query,get the random id from the previous query's result and show the entire row of relevant id.And I got stuck at random function.
If I need to explain this work with percentage for to be more clearly,

Works well and get results %70
get empty %20
get null array [] %10

I wanted the show the screenshots but system didn't give the permission because of my reputation.So,the final statement as usual,"I'm not so good at PHP.Any idea?" Honestly,any help would be appreciated.

A:

Your should wait for array to get filled inside your while loop and then get random value from it.
while ($resultsFirst = $dbQueryFirst->fetch(PDO::FETCH_ASSOC)) 
{
    $getidFirst[] = $resultsFirst;     
}

$puppet = array_rand($getidFirst);
$rndID = $getidFirst[$puppet];

Also, you can get random entry directly from your database without using php.
$dbQueryFirst = $nesnePDO->prepare("SELECT CategoryID FROM Categories ORDER BY RAND() LIMIT 1");
$dbQueryFirst->execute();  
$rndID = $dbQueryFirst->fetch(PDO::FETCH_ASSOC)

By the way, you should be getting your CategoryID like so
$rndID['CategoryID']

