这是一个类似于我使用的简化代码。在这一个中,我从ID中提取姓名。
$counter = 0;
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
$maxusers = 10;
while($counter<$maxusers) {
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
我得到的是同一个名字,select语句中的计数器保持为0.
我必须将$ select语句的定义和$ result放在循环中,每次进入while循环时它都会重新定义所有内容,如下面的代码所示。这对我来说似乎不切实际和最佳。对于像这样的情况,最好的解决办法是什么?我并不熟悉PHP中的变量范围,在sql函数方面我还没有找到任何关于这个问题的好文档。
$counter = 0;
$maxusers = 10;
while($counter<$maxusers) {
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
这是我实际编写的代码。
$selectFirst = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter AND nDateTime BETWEEN $today AND $tomorrow";
$selectLast = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter DateTime BETWEEN $today AND $tomorrow DESC";
$resultFirst = sqlsrv_query($bscon, $selectFirst);
$resultLast = sqlsrv_query($bscon, $selectLast);
$selectnumberofUsers = "SELECT TOP 1 nUserIdn FROM TB_USER ORDER by nUserIdn DESC";
$usersmaxq = sqlsrv_query($bscon, $selectnumberofUsers);
$usersmax = sqlsrv_fetch_object($usersmaxq)->nUserIdn;
while($usercounter<$usersmax){
$usercounter = $usercounter + 1;
while($rowfirst = sqlsrv_fetch_array($resultFirst)) {
$intime = $rowfirst['nDateTime'];
}
echo $intime." ".$usercounter."<br />";
}
答案 0 :(得分:0)
您的问题与变量范围无关。 $ select变量设置为字符串,其当前值为$ counter。您的第二个示例有效,因为每次都会重置此值。 然而,在你的第二个例子中,你正在创建一个获得1行的sql语句(假设nID是唯一的),然后循环遍历你的结果检索那一行。您正在进行10次SQL调用,但如果修改查询,则只需要一次:
$minusers = 0;
$maxusers = 10;
$select = "SELECT nID,nName WHERE nID >= $minusers AND nID < $maxusers ORDER BY nID";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
对于您的实际代码,您应该能够使用GROUP BY为每个nUserId获取一条记录。试试这个:
$selectFirst = "SELECT nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID >= $usersmin AND nUserID <= $usersmax AND nDateTime BETWEEN $today AND $tomorrow GROUP BY nUserID";