drsfgwuw61488 2015-07-05 12:09
浏览 134
已采纳

array_rand函数有时会返回空

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.

  • 写回答

2条回答 默认 最新

  • doulao3905 2015-07-05 12:23
    关注

    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']
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符