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

时间:2013-08-03 14:27:27

标签: php

我有这个小小的代码,最终发送到MySQL数据库。其余的代码是合理的,但是这段代码喜欢在某些时候给我空数据。有什么办法可以防止这种情况发生吗?

编辑:这是整个块

//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 个答案:

答案 0 :(得分:1)

首先,你的if条款似乎有点多余。更简洁的代码:

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

这应该总是返回一个值 - 如果其他一切都失败了,"3"

甚至可能更好:

$one_genetics = ($one_gene + 1) / 2; // integer division

答案 1 :(得分:0)

我不知道你在做什么,但maby你可以看看这个:

<?php

    $animals = array();

    $animals[] = array('dog', 78, array('Komondor','Old English Sheepdog'));    
    $animals[] = array('Drosophila', 8, array('Vestigal','Ebony')); 

    $number_animals = count($animals) - 1;
    $list_size = 30;

    for($q = 1; $q <= $list_size; $q++){

        $rand = rand(0, $number_animals);
        $animal = $animals[$rand];

        $number_species = count($animal[2]) - 1;

        $rand = rand(0, $number_species);
        $randsex = rand(0, 1);

        $species = $animal[2][$rand];
        $sex = ($randsex ? 'male' : 'female');
        $genes = $animal[1];

        echo "$q: $species - $sex - $genes <br>";
    }

?>

观看现场演示:here

如果您希望根据自己的意愿修改随机动物的规格。