2017-02-28 100 views
0

我的SQL表爲什麼我的變量在TCPDF中未定義?

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

我創建TCPDF一個pdf:

$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>' 
; 

我希望得到的結果是140,但我得到一個錯誤信息:

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

注意:如果我刪除+標誌。 PDF格式創建時沒有錯誤,我得到結果70

+1

make $ result = 0;在$ pdo-> execute()之後;現在你試圖添加一些不存在的變量:) – barat

+0

[PHP:「注意:未定義的變量」,「注意:未定義的索引」和「注意:未定義的偏移量」)(http:// stackoverflow .com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – miken32

回答

2

它在錫上表示:$result在第一次循環訪問數據時沒有定義。你不能添加任何東西,因爲它尚未定義。這應該工作。

$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'];  
    } 
+0

是的,這確實奏效! – Jarla

2

上線

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

你讓這個

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

但你運行該腳本的第一次,沒有定義$ result變量中。 添加

$result = 0; 

的$ PDO連接之前或同時,之前,你不應該有任何錯誤了。

+0

謝謝,這是工作 – Jarla

相關問題