while looping vs foreach looping

Im trying to print it in excel but I dont get it why the foreach loop give me an Warning: Illegal string offset but in while loop it just run smoothly

this is the while loop

EDITED

include 'db.php';
$sql = "SELECT * FROM customer";
$result = mysql_query($sql);
$excel = array();

while($row = mysql_fetch_array($result)){
    $wew = $row["fname"]."\t".$row["lname"]."\t".$row["email"];
    array_push($excel,$wew);
}

echo implode("\n",array_values($excel));

This is my foreach loop

include 'db.php';
$sql = "SELECT * FROM customer";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$excel = array();

foreach($row as $r){
    $wew = $r["fname"]."\t".$r["lname"]."\t".$r["email"];
    array_push($excel,$wew);
}

echo implode("\n",array_values($excel));

Im trying to understand it but couldn't find how solve this one.

Upvotes: 1

Views: 322

Answers (1)

Irvin
Irvin

Reputation: 850

Your $r is of string type and not an array so:

foreach($row as $r){
    $wew = $row["fname"]."\t".$row["lname"]."\t".$row["email"];
    array_push($excel,$wew);
}

OR

$wew = "";
foreach($row as $r){
    $wew .= $row["fname"]."\t".$row["lname"]."\t".$row["email"]; 
}
array_push($excel,$wew);

Upvotes: 2

Related Questions