Notice: Array to string conversion - PHP & mySQL

2020-03-04 02:30发布

问题:

I've been reading in every thread in here that is related to this but I always get it wrong.

Please help cause I always get the error

"Notice: Array to string conversion" in line "$address[] = mysql_result($row, 0 );"

below. Please help.

if ($p_address=mysql_query($email))
{
$address = array();

while($row = mysql_fetch_assoc($p_address))
{     
 $address[] = mysql_result($row, 0 );
}  

$all_address = implode(',', $address);

回答1:

Change this line

 $address[] = mysql_result($row, 0 );

To this:

 $address[] = $row;

And then to see the keys and values available in the new $address array, you can do something like this:

 print_r($address);

In order to keep implode() functional, do something like this:

for ($i = 0; $i < count($address); $i++) {
  $all_address[] = implode(',', $address[$i]);
}

Final output:

if ($p_address=mysql_query($email))
{
$address = array();

while($row = mysql_fetch_assoc($p_address))
{     
 $address[] = $row;
}

for ($i = 0; $i < count($address); $i++) {
  $all_address[] = implode(',', $address[$i]);
}

// Example for outputting on screen:
foreach ($all_address as $aa) {
  print $aa . "<br/>\n";
}
}

Hope that helps...



回答2:

$row is set in every iteration of the while loop. every time it contains a new table record. So you just need to add each record in the address array.

   while($row = mysql_fetch_assoc($p_address))
   {     
      $address[] = $row;
   }