douxie1894 2014-02-12 15:49
浏览 37
已采纳

随机函数产生重复结果

I'm working on a script to install sample data into a database. I have a script I coded I call "Generic Data Generator". This PHP file includes a variety of functions to generate random data.

Example function:

// Random number generator.
function gdg_number( $number_start, $number_end ) {

    return rand( $number_start, $number_end );
}

Example query:

function gdg_values( $results ) {

    $values = "";

    for ( $i = 1; $i <= $results; $i++) {
        $values .= "
            '" . gdg_sentence(3,12) . "',
            '" . gdg_multi_paragraphs(1,5,5,8,4,17) . "',
            '" . gdg_multi_paragraphs(1,5,5,8,4,17) . "',
            '" . gdg_number(100,900) . "." . gdg_number(00,99) . "',
            '" . gdg_number(1,20) . "',
            '" . gdg_number(0,50) . "',
            '" . gdg_string(10,10) . "',
            '0'
        ), (";
    }

    return $values;
}

$value = gdg_values( 100 );
$values = substr( $value, 0, -4);

The problem I'm experiencing is when I view the MySQL table after I use the script to insert multiple rows, I notice there is duplicate data entries. Entire rows have the same values for each column.

What could cause the gdg_values() to produce identical results every 3 rows? (Notice, it does this even if I manually copy/paste the $values repeatedly directly into the MySQL query.

Here is the full generic_data_generator.php file.

http://pastebin.com/jjRF8SZd

Here is the full products.php file which is included in the install script for the database to install sample data into the products MySQL table.

http://pastebin.com/TtkstXgS

展开全部

  • 写回答

2条回答 默认 最新

  • doutang1856 2014-02-12 16:00
    关注

    As stated at Is rand() time-dependent in php?:

    Note that the automatic seeding seems to be done with the current number of seconds which means you can get the same results for several runs on a fast server. Either call srand() yourself with a more frequently changing seed or use mt_rand() which doesn't appear to suffer from the problem.

    Therefore, you can either use:

    function gdg_number( $number_start, $number_end ) {
        return mt_rand( $number_start, $number_end );
    }
    

    Or, you can use:

    function gdg_number( $number_start, $number_end ) {
        srand();
        return rand( $number_start, $number_end );
    }
    

    Both of which should create a different random value more often.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部