1

The following code produces an illegal offset error every time the while() loops:

Warning: Illegal string offset 'username' in /Applications/MAMP/htdocs/admin/scripts/email_owners_send.php on line 48

I'm trying to set $name to be $email['username'] if $email['username'] isn't empty, and if is empty, $name should be set to $email. $email is set by the while() statement, from a mysql_fetch_assoc(). This is my code at the moment:

// 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 .=',';
    }
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
James
  • 1,088
  • 3
  • 11
  • 29
  • 1
    Please, [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and consider using [PDO](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard May 04 '15 at 19:12

2 Answers2

2

You are overwriting the $email variable set by the while loop

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

then here you are overwriting it:

$email = $email['email'];

so $email will become a string and not an array. You could change this to

$email_address = $email['email']
NaN
  • 697
  • 5
  • 11
1

You have an array named $email which holds all the columns in your database row. And you are overwriting that object with the value of only the email column:

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

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

Don't do that. It would make a lot more sense to call the row object $row. You should name variables so that its obvious what they are.

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

    // set email
    $email = $row['email'];
...
developerwjk
  • 8,619
  • 2
  • 17
  • 33