Ahmed Ebaid
Ahmed Ebaid

Reputation: 417

Showing the value of an array?

<?php
    $result = $mysqli->query(SELECT SUM(Answer) as answer FROM answers WHERE SID ='$uname'");
            $Sum = $result->fetch_row();
    var_dump($Sum);
?>

When executing the above code I get the following: Array ( [SUM(Answer)] => 8 ), however, when I try to access $Sum[0] I get the following Undefined offset: 0 and it prints nothing. I need to use this variable in an echo statement. Also, $Sum['Answer'] prints nothing, and I got a message saying undefined index Answer.

Upvotes: 0

Views: 65

Answers (3)

nullability
nullability

Reputation: 10675

mysql_fetch_assoc returns an associative array, not a numeric array, so 0 will be an undefined index. PHP arrays do not automatically have numeric indices, unlike other languages.

If you want to use a numeric index, you should use mysql_fetch_array to get an array with both associative and numeric indices. If you need to stick with the associative array, however, you need to use the appropriate key:

$Sum['SUM(Answer)'];

The key is unusual because your SQL doesn't give SUM(Answer) a name so I would recommend that you update it to have one:

$SQL = "SELECT SUM(Answer) as answer FROM answers WHERE SID ='$uname' ";

Upvotes: 4

Markus Hofmann
Markus Hofmann

Reputation: 3447

TIP: Always have a look in the PHP Manual.

The mysql_fetch_assoc() extension is deprecated as of PHP 5.5.0, because the MySQLi and PDO extensions should be used instead. Just to quote the manual

If you want to debug your code use:

echo '<pre>' . print_r($result, true) . '</pre>';

This will echo the array / object formatted, so it'll be easier for you to read.

var_dump will be less readable as it shows types (e.g. string) and string length.

The PHP Arrays Manual will teach you more on how to use arrays.

Happy reading :-)

Upvotes: 0

qJake
qJake

Reputation: 17139

If you want to print the value of an array or object and show all of its members / properties, use the print_r function.

print_r($Sum);

or, for better formatting on a webpage:

echo '<pre>' . print_r($Sum, true) . '</pre>';

After your edit: The var_dump is correct, you need to access your column by its name, like this:

$Sum['SUM(Answer)']

If you don't like this, change the name of your column (SELECT SUM(Answer) AS sum FROM... or something like that, then you can do $Sum['sum']).

Upvotes: 3

Related Questions