My Sql Table
我的Sql表
+------------+---------+
| name | price |
+------------+---------+
| A | 70 |
+------------+---------+
| B | 70 |
+------------+---------+
I create a pdf with TCPDF:
我用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>'
;
I expect the result to be 140
, but I get an error message:
我希望结果是140,但是我得到了一个错误信息:
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
.
注意:如果我删除+号。pdf是在没有错误的情况下创建的,我得到的结果是70。
2 个解决方案
#1
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.
它执行它在tin上的操作:$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'];
}
#2
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变量没有定义。添加
$result = 0;
before the $pdo connection or before the while and you should not have any errors anymore.
在$pdo连接之前或之前,您应该不会再有任何错误。
#1
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.
它执行它在tin上的操作:$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'];
}
#2
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变量没有定义。添加
$result = 0;
before the $pdo connection or before the while and you should not have any errors anymore.
在$pdo连接之前或之前,您应该不会再有任何错误。