我使用此代码循环遍历 MySQL 行:
$sql = "SELECT * FROM vwPublicServices2 ORDER BY Service_Date__c,
Service_Time__c";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Service Date</th><th>Service Time</th>
<th>Church</th><th>Service</th><th>Service Leader</th></tr>";
while($row = $result->fetch_assoc()) {
// insert header stuff on change of $date1
if ($row["ServiceDate"] <> $date1) {
echo $row["ServiceDate"]. "(".$date1.")"."<br/>";
echo "<tr><td>" . $row["ServiceDate"]. "</td><td>" .
$row["Service_Time__c"]. "</td><td>" . $row["Location__c"]. "</td>
<td>" . $row["PublicName"]. "</td><td>" . $row["FullName"]."</td>
</tr>";
// set $date1 = row ServiceDate
$date1 = $row["ServiceDate"];
} else {
// echo row data to follow on previous - i.e date has not
changed
echo "<tr><td>" .
$row["ServiceDate"]. "</td><td>" .
$row["Service_Time__c"]. "</td><td>" .
$row["Location__c"]. "</td><td>" .
$row["PublicName"]. "</td><td>" .
$row["FullName"]."</td></tr>";
}
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
每次 row["ServiceDate"] 更改时,我想插入一些标题数据。 以下是一些结果:
有两件事我无法理解 - 为什么日期检查是“一个日期”,即在第二行中为什么是 14/05/2017 与 13/05/2017 相比?
另外,为什么第二个 echo 语句没有出现?
我认为我错过了 while 循环工作方式的一些基本点!非常感谢这里的任何帮助。谢谢。
以下是使用与上面类似的数据在日期更改时插入 header 的说明。 (此网页通过 Salesforce 的 API 从 Salesforce 提取数据,并使用与上面 MySQL 代码中类似的日期检查 - 但它使用 For..Each 循环遍历数据)
最佳答案
以下是包含 moni_dragu 代码的完整代码:
<style>
table, th, td {
border: 1px solid black;
}
</style>
<?php
$servername = "****";
$username = "****";
$password = "****";
$dbname = "*****";
$date1="01/01/1900";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM vwPublicServices2 ORDER BY Service_Date__c,
Service_Time__c";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table>";
while($row = $result->fetch_assoc()) {
// insert header stuff on change of $date1
if ($row["ServiceDate"] <> $date1) {
echo "<tr><th>".$row["ServiceDate"]. "(".$date1.")"."</th></tr>";
echo "<tr><th>Service Date</th><th>Service Time</th>
<th>Church</th><th>Service</th><th>Service Leader</th></tr>";
$date1 = $row["ServiceDate"];
}
// echo row data
echo "<tr><td>" .
$row["ServiceDate"]. "</td><td>" .
$row["Service_Time__c"]. "</td><td>" .
$row["Location__c"]. "</td><td>" .
$row["PublicName"]. "</td><td>" .
$row["FullName"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
再次感谢您解决了问题,并加深了我对 MySQL 记录集的 while 循环的理解。
关于php循环遍历MySQL记录-根据行值做出决定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43933049/