未定义的变量$ count

时间:2015-01-24 23:55:18

标签: php variables undefined

我收到了一个非常烦人的错误Undefined variable: count。这是我的代码:

<?php
    $user = getUserData('Username');
    $sql = "SELECT `Username`, `Uplata`, `Dobivka`, `Date` FROM `kladilnica` WHERE `Username`='$user'";
    $result = $conn->query($sql);
    if($result === false) {
        echo "<b>Could not connect to database.</b>";
        trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
    } else {
        if($result->num_rows == 0) {
            echo "<b>Something went wrong try again later.</b>";
        } else if($result->num_rows >= 1) {
            echo "<table id='t01'><tr><th>ID</th><th>Username</th><th>Uplata</th><th>Dobivka</th><th>Date</th></tr>";
            while($row = $result->fetch_assoc()) {
                $count = $count + 1;
                echo "<tr><td>".$count."</td> <td>".$row["Username"]."</td> <td>".$row["Uplata"]."</td> <td>".$row["Dobivka"]."</td> <td>".$row["Date"]."</td></tr>";
            }
                echo "<tr><th colspan='5'>Vkupna Uplata:</th></tr>";
                echo "<tr><th colspan='5'>Vkupna Dobivka:</th></tr>";
                echo "</table>";
            }
        }
    $conn->close();
    ?>

3 个答案:

答案 0 :(得分:3)

在尝试使用$count递增之前,您需要将$count = $count + 1初始化为某个值。您可以将while循环更改为for循环,并在$count语句中初始化for

for ($count = 0; $row = $result->fetch_assoc(); $count++){
    // do something
}

答案 1 :(得分:1)

您正在阅读表达式$count中的变量$count + 1。在while循环的第一次迭代中,变量尚未分配,这会导致您的错误。您无法读取/使用尚未定义的变量。

解决方案很简单:在循环之前将$count初始化为0

$count = 0;
while($row = $result->fetch_assoc()) {
   $count = $count + 1;
   echo "<tr><td>".$count."</td> ......";
}

答案 2 :(得分:-3)

我建议改变

$count = $count + 1;

$count+=1;

这应该可以解决问题。