0

My Sql Table

+------------+---------+
|    name    |  price  |
+------------+---------+
|     A      |    70   |
+------------+---------+
|     B      |    70   |
+------------+---------+

I create a pdf with TCPDF:

$pdo = $db->prepare("SELECT * FROM table");  
    $pdo->execute(); 
    while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {  
        $result += $row['price'];       
} 

$html = '
<table><tr><th>'.$result.'</th></tr></table>'
;

I expect the result to be 140, but I get an error message:

Notice: Undefined variable: result 
TCPDF ERROR: Some data has already been output, can't send PDF file

Note: If I remove the + sign. The pdf is created without errors and I get the result 70.

peace_love
  • 6,229
  • 11
  • 69
  • 157
  • 1
    make $result = 0; after $pdo->execute(); Now You're trying to add something to not-existent variable :) – barat Feb 28 '17 at 15:30
  • Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – miken32 Feb 28 '17 at 23:27

2 Answers2

2

It does what it says on the tin: $result is not defined the first time you loop through your data. You can't add anything to it, because it's not defined yet. This should work.

$pdo = $db->prepare("SELECT * FROM table");  
    $pdo->execute(); 
    $result = 0.0; // Add this row. I'm assuming 'price' is a decimal
    while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {  
        $result += $row['price'];       
    }
Ben Hillier
  • 2,126
  • 1
  • 10
  • 15
2

On the line

$result += $row['price'];

You make this

$result = $result + $row['price'];

But the very first time you run the script, the $result variable is not defined. Add

$result = 0;

before the $pdo connection or before the while and you should not have any errors anymore.

Simone Cabrino
  • 901
  • 9
  • 24