【问题标题】:"Illegal offset" inside of loop [duplicate]循环内的“非法偏移”[重复]
【发布时间】:2015-07-14 07:24:57
【问题描述】:

以下代码在每次while() 循环时都会产生非法偏移错误:

警告:第 48 行 /Applications/MAMP/htdocs/admin/scripts/email_owners_send.php 中的非法字符串偏移“用户名”

如果$email['username'] 不为空,我正在尝试将$name 设置为$email['username'],如果为空,则$name 应该为设置为$email$emailwhile() 语句设置,来自mysql_fetch_assoc()。这是我目前的代码:

// print out all the email address recipients
$query = mysql_query("SELECT * FROM ownersemails WHERE deleted=0 LIMIT 5");
$recipients = '';
$total = mysql_num_rows($query);
$num = 0;
while($email = mysql_fetch_assoc($query)) {
    // add to count
    $num++;

    // set email
    $email = $email['email'];

    // set name as username if apparant
    if(!empty($email['username'])) {
        $name = $email;
    }
    else {
        $name = $email['username'];
    }

    // add to recipients string (=. append)
    $recipients .= '{ "email": "'.$email.'", "name": "'.$name.'" }';
    // only add a comma if it isn't the last one
    if($num!=$total) {
        $recipients .=',';
    }
}

【问题讨论】:

标签: php mysql email loops while-loop


【解决方案1】:

您有一个名为$email 的数组,其中包含数据库行中的所有列。而且您正在使用仅电子邮件列的值覆盖该对象:

while($email = mysql_fetch_assoc($query)) {
    // add to count
    $num++;

    // set email
    $email = $email['email'];
...

不要那样做。调用行对象$row 会更有意义。您应该命名变量,以便清楚它们是什么。

while($row = mysql_fetch_assoc($query)) {
    // add to count
    $num++;

    // set email
    $email = $row['email'];
...

【讨论】:

    【解决方案2】:

    您正在覆盖由 while 循环设置的 $email 变量

     while($email = mysql_fetch_assoc($query)) {
    

    那么你在这里覆盖它:

    $email = $email['email'];
    

    所以$email 将成为一个字符串而不是一个数组。您可以将其更改为

    $email_address = $email['email']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      • 2019-03-01
      • 2013-02-19
      • 2012-01-07
      • 2020-04-21
      • 2021-04-25
      相关资源
      最近更新 更多