将while语句更改为foreach

时间:2011-10-13 16:02:07

标签: php foreach while-loop

我有一个正确执行的while语句,但它需要是一个foreach语句,因为有多个插入,并且它不生成随机密码或为每个插件发送电子邮件。这是代码:

        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 <noreply@yourcompany.com>\nContent-Type: text/html");

            }

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

2 个答案:

答案 0 :(得分:3)

我认为你的while循环没有任何问题 - 你太早关闭了句柄! fclose和最后echo行应位于最后一个大括号之后。

答案 1 :(得分:0)

我可以看到您没有定义用于发送电子邮件的变量的问题:

$ln_first $ln_last <$ln_email>

我看不出这些变量的来源,也不知道这些

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