user880789
user880789

Reputation: 171

Change a while statement to a foreach

I have a while statement that's executing correctly but it needs to be a foreach statement since there are multiple inserts being made and it's not generating the random password or sending the email for each. Here's the code:

        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
     {

        $password = createRandomPassword(); 

        // Add the user to the database:
        $sql = "INSERT into users(account_id,first,last,email,pass) values('$id', '$data[0]','$data[1]','$data[2]','$password')";
        $r = mysqli_query ($dbc, $sql) or trigger_error("Query: $sql\n<br />MySQL Error: " . mysqli_error($dbc));


            if (mysqli_affected_rows($dbc) == 1) { // If it ran OK.

                    $emailBody = "<html><body>";

                    $emailBody .= "<br><br><b>Hey $first $last!</b>";

                    $emailBody .= "<br><br>You've been added to our site and your password is: $password";

                    $emailBody .= "</body></html>";

                    mail("$ln_first $ln_last <$ln_email>", "Your Account" , $emailBody, "From: YourCompany <[email protected]>\nContent-Type: text/html");

            }

     fclose($handle);
    echo '<p><div class="alert green">You have successfully imported users.</div></p>';
 }

Upvotes: 0

Views: 71

Answers (2)

Frank
Frank

Reputation: 534

The problems as I can see that you haven't defined the variables you're using to send the emails:

$ln_first $ln_last <$ln_email>

I cannot see where these variables came from, nor these

$emailBody .= "<br><br><b>Hey $first $last!</b>";

Upvotes: 0

JoLoCo
JoLoCo

Reputation: 1375

I don't think there's anything wrong with your while loop - you're closing the handle too early! The fclose and final echo lines should be after that final curly bracket.

Upvotes: 3

Related Questions