2

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

3
  • 1
    how do I get it back now that each line of the CSV file gets its own random number move $gencode = generateCode(8); inside the loop Commented May 24, 2015 at 20:01
  • 1
    Hello. I have solved the problem already own. As I thought. I was too long on it and then have overlooked something. One should not pack doe entire function in the While Loop only "$gencode = generateCode (8);" Thus, the entire while loop should look like this. while (($data = fgetcsv ($ handle, 10000, ";")) == FALSE) { $gencode = generateCode (8); $ import = "INSERT into jobs (id, link_id, randomnumber) values ('NULL', '$ linkid', '$gencode')"; mysql_query ($ import) or die (mysql_error ()); } Commented May 24, 2015 at 20:04
  • @SkysTheLimit_81 - If one of the answers bellow has helped you, please select it as the answer for your question, otherwise if you found the solution yourself you can post it as an answer and later accept it. Commented May 24, 2015 at 20:15

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.