如何从PHP中的函数访问while循环中的变量?

myo*_*yom 0 php variables while-loop

我想$name在名为的函数中访问变量,该变量在while循环中定义sendMail.我是否必须以某种方式将函数合并到循环中?

<?php
while ($row = mysql_fetch_assoc($result))
{
    print_r($row); echo "<br><br>";
    $name = $row['Name'];
    $date = $row['sDate'];
    $time = $row['sTime'];
    $phone = $row['Phone'];

    $email = $row['Email'];
    sendMail($row['Email']);

    $company = $row['Company'];
    $course = $row['Course'];
    $ref = $row['Reference'];
    $optout = $row['optout'];

    echo "<tr bgcolor=#ABB5F6>
    <td>$name</td>
    <td>$date</td>
    <td>$time</td>
    <td>$phone</td>
    <td>$email</td>
    <td>$company</td>
    <td>$course</td>
    <td>$ref</td>
    <td>$optout</td>
    </tr>";
}

// Mail to $to and $emailarray recipients
function sendMail($to)
{
    $subject = 'Test mail';
    $message = 'Hello'.$name; // I want $name from the while loop
    $headers = array();
    $headers[] = "From:" . "myemail@email.com";
    $headerz = implode("\r\n", $headers);

    mail($to, $subject, $message, $headerz);
}

?>
Run Code Online (Sandbox Code Playgroud)

Rud*_*ser 5

要么sendMail()接受一个数组(即$row), or add another parameter tosendMail()which is called$ name`并传入它.

即.

function sendMail($to, $name)
Run Code Online (Sandbox Code Playgroud)

叫做:

sendMail($row['Email'], $row['Name']);
Run Code Online (Sandbox Code Playgroud)

参数可能是最简单的,不要沿着全局变量的路线走.我建议不要使用该数组,因为格式未定义,如果您的表结构可以更改.如果您使用mysql_fetch_object强定义的类,那么这将是最可接受的解决方案(当然,也使用PDO/MySQLi)...特别是如果您计划在$row未来扩展使用更多数据.


Mat*_*lin 5

为什么不直接将$ name传递给sendMail函数:

// Mail to $to and $emailarray recipients
function sendMail($to, $name)
{
    $subject = 'Test mail';
    $message = 'Hello'.$name; // I want $name from the while loop
    $headers = array();
    $headers[] = "From:" . "myemail@email.com";
    $headerz = implode("\r\n", $headers);

    mail($to, $subject, $message, $headerz);
}
Run Code Online (Sandbox Code Playgroud)

然后使用name变量调用sendMail函数?


Arc*_*ien 5

为什么不通过呢?

function sendMail($to, $name);
Run Code Online (Sandbox Code Playgroud)

并打电话

sendMail($row['Email'], $row['name']);
Run Code Online (Sandbox Code Playgroud)