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?

4
  • <?php echo "<pre/>";print_r( $line); ?> or <?php var_dump( $line); ?>or <?php print( $line); ?> and stop using mysql_*. Use mysqli_* or PDO Commented Mar 12, 2016 at 16:29
  • Don't use mysql_* functions as they are deprecated and have major security holes. Commented Mar 12, 2016 at 16:34
  • RTM: mysql_fetch_array: Returns an array of strings that corresponds to the fetched row..., you can't echo an array. Commented Mar 12, 2016 at 16:35
  • Please, take a look at Why shouldn't I use mysql_* functions in PHP? Commented Mar 12, 2016 at 16:37

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

wow!!! i use: echo $line['average']; and it's working!!! thank you:)) you're a master

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.