只能循环一次SQL行?

时间:2018-09-30 15:18:39

标签: php mysqli

我不知道如何保持执行状态。 // CALCULATE EACH MONTH中的代码仅在tracks的第一个循环上执行。

我有一个想法,需要将SQL结果存储在数组中?但是我真的无法正常工作。

我的php代码是:

$conn = new mysqli($servername, $username, $password, $dbname);
$monthsQuery = "SELECT DISTINCT YEAR(`Reporting Date`) AS `Year`, MONTH(`Reporting Date`) AS `Month` FROM tsv ORDER BY `Reporting Date`";
$monthsResult = $conn->query($monthsQuery);


if(isset($_POST['submit'])) {
    $tracks = $_POST['track'];
    $albums = $_POST['album'];
    foreach($tracks as $track) {
        echo "Partof:" . $track['partof'] . "<br>"; 
        echo "percentage:" . $track['percentage'] . "<br>";
        // CALCULATE EACH MONTH
        if ($monthsResult->num_rows > 0) {
            // output data of each row
            $i = 0;
            while($monthRow = $monthsResult->fetch_assoc()) {
                $monthNum  = $monthRow["Month"];
                $dateObj   = DateTime::createFromFormat('!m', $monthNum);
                $monthName = $dateObj->format('F'); // March
                echo $monthRow["Year"] . " " . $monthName . "<br>";
                $i++;
            }
        } else {
            echo "0 results";
        }
        //END MONTH CALCULATION

1 个答案:

答案 0 :(得分:1)

我在这里建议做的是读取所有行并将其保存到foreach循环之前的数组中:

android:ems="10"