Reputation: 21
I'd like to run a function within a While loop. Unfortunately, it works but not quite as desired.
My goal is to read out from a CSV file, each line and is stored in the MySQL database. This also works flawlessly.
In addition, however, I want to let miteinpflegen a value by a numeric random.
Here again my scripts to generate the numerical codes.
function generateCode($length){
$string = "";
$numbers = "0123456789";
for($i=0;$i < $length;$i++) {
$char = $numbers[mt_rand(0, strlen($numbers)-1)];
$string .= $char;
}
return $string;
}
$gencode = generateCode(8);
Works great.
And here my while loop ($handle is in my case the var to open CSV file)
while (($data = fgetcsv($handle, 10000, ";")) !== FALSE) {
$import = "INSERT into jobs(id,link_id,random number) values('NULL','$linkid','$gencode')";
mysql_query($import) or die(mysql_error());
}
But how do I get it back now that each line of the CSV file gets its own random number or rather, which is calculated in each row $gencode new? At the moment i get one random number for all rows.
For help, I am very grateful. I just can no longer see the forest for the trees.
Thank you
Upvotes: 2
Views: 1669
Reputation: 42460
You can simply call your own function generateCode()
like any other function inside your loop:
while (($data = fgetcsv($handle, 10000, ";")) !== FALSE) {
$gencode = generateCode(8);
// the rest of your code
}
Just make sure that generateCode()
is already defined when you call it.
Upvotes: 2