1

I want to get the average of a column in a table,

table: buy column: c1

when I called the database with this:

$query="Select AVG(c1) as average FROM buy";
$result_array=mysql_query($query);
$line = mysql_fetch_array($result_array);

and when I called with php like this

<?php echo $line; ?>

it came up error with this message

Array to string conversion in .......... on line 50 Array

what did I do wrong? I think because I treated arrays as a string. but how can i fix this?

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
gtviga
  • 91
  • 5
  • `";print_r( $line); ?>` or ``or `` and stop using `mysql_*`. Use `mysqli_*` or `PDO` – Alive to die - Anant Mar 12 '16 at 16:29
  • Don't use `mysql_*` functions as they are deprecated and have major security holes. – Ikari Mar 12 '16 at 16:34
  • RTM: [mysql_fetch_array](http://php.net/manual/en/function.mysql-fetch-array.php): _Returns an array of strings that corresponds to the fetched row..._, you can't `echo` an `array`. – FirstOne Mar 12 '16 at 16:35
  • Please, take a look at [**Why shouldn't I use mysql_* functions in PHP?**](http://stackoverflow.com/q/12859942/4577762) – FirstOne Mar 12 '16 at 16:37

1 Answers1

1

Please take a look that $line returns an array. So, you can't echo an array. One thing you can do is

echo "<pre>";
print_r($line);

Check what the array looks like.

Is it a single row that's been returned? In that case you can write

echo $line['average'];

If it's more than one row:

while ($line = mysql_fetch_array($result_array)) {
   echo $line['average'];
}

Hope this helps.

Peace! xD

Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32