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.
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.
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.
This is not an answer but probably too long for a comment.
Make sure that your text fields are properly escaped. I don't know what your text generating functions are doing but their output needs to be run through mysql_real_escape_string
(actually, you should be using the mysqli
functions instead).
Your product_price
field is an integer but you are inputting a decimal number.
The function gdg_number
in not needed since it just returns rand
with exactly the same arguments. Kill that function and just use rand
.
Use 0 instead of 00. OK, it probably makes no difference but a leading 0 means octal.