douhuan1905 2013-08-03 14:27
浏览 95
已采纳

PHP rand函数给出空值 - 仍然无法正常工作

I have this little tid-bit of my code, which is eventually sent to a MySQL database. The rest of the code is sound, but this code likes to give me empty data some of the time. Is there any way to prevent this from happening?

Edit: Here's the whole chunk

//random Species
$sp_one = mt_rand(1,10);    
$one_species = "Water Leaper";

//random Genetics

if($one_species == "Water Leaper")
{
    $one_gene = mt_rand(1,5);

    if($one_gene < 3)
    {
        $one_genetics = "1";
    }

    else if($one_gene < 5)
    {
        $one_genetics = "2";
    }

    else
    {
        $one_genetics = "3";
    }
}

//random Gender
$one_sex_num = mt_rand(1,2);

if($one_sex_num == 1)
{
    $one_gender = "Female";
}

if($one_sex_num == 2)
{
    $one_gender = "Male";
}

//Entering it
$sql="INSERT INTO creatures (species, sex, location, genetics)
VALUES('{$one_species}','{$one_gender}', 's1','{$one_genetics}')";

mysqli_query($con,$sql);
  • 写回答

2条回答 默认 最新

  • dongyan1936 2013-08-03 14:34
    关注

    First, your if clauses seem a bit redundant. More concise code:

    if ($one_gene <3)      { $one_genetics = "1"; }
    elseif ($one_gene <5)  { $one_genetics = "2"; }
    else                   { $one_genetics = "3"; }
    

    This should always return a value - if everything else fails, "3".

    Maybe better even:

    $one_genetics = ($one_gene + 1) / 2; // integer division
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错
  • ¥15 java python或者任何一种编程语言复刻一个网页
  • ¥20 如何通过代码传输视频到亚马逊平台
  • ¥15 php查询mysql数据库并显示至下拉列表中
  • ¥15 freertos下使用外部中断失效
  • ¥15 输入的char字符转为int类型,不是对应的ascall码,如何才能使之转换为对应ascall码?或者使输入的char字符可以正常与其他字符比较?
  • ¥15 devserver配置完 启动服务 无法访问static上的资源
  • ¥15 解决websocket跟c#客户端通信