Php 更改while循环,使echo不会';不要打印多次
我有一些代码,echo是while循环中的一行文本。但是我不希望它作为一个循环,并且似乎无法在没有while()的情况下让它工作。我的代码如下-如何才能让echo只打印一次Php 更改while循环,使echo不会';不要打印多次,php,Php,我有一些代码,echo是while循环中的一行文本。但是我不希望它作为一个循环,并且似乎无法在没有while()的情况下让它工作。我的代码如下-如何才能让echo只打印一次 while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) { do($row['InGarage'] == $comp and $row['BeingServiced'] == $unco and $row['ReadyForCollection'] ==
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
do($row['InGarage'] == $comp and $row['BeingServiced'] == $unco and $row['ReadyForCollection'] == $unco) {
echo "Vehicle is in Garage<br />";
}
do($row['InGarage'] == $comp and $row['BeingServiced'] == $comp and $row['ReadyForCollection'] == $unco) {
echo "Vehicle is being serviced<br />";
}
do($row['InGarage'] == $comp and $row['BeingServiced'] == $comp and $row['ReadyForCollection'] == $comp) {
echo "Vehicle is ready for collection<br />";
}
}
不需要
do
运算符,但需要while
来迭代数据库中的所有结果。与其使用do
,不如使用if
。您还可以重构条件以创建稍短的条件:
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
if ($row['InGarage'] == $comp) {
if ($row['BeingServiced'] == $comp) {
if ($row['ReadyForCollection'] == $unco) {
echo "Vehicle is being serviced<br />";
}
elseif ($row['ReadyForCollection'] == $comp) {
echo "Vehicle is ready for collection<br />";
}
}
elseif ($row['BeingServiced'] == $unco and $row['ReadyForCollection'] == $unco) {
echo "Vehicle is in Garage<br />";
}
}
}
if($row['InGarage'] == $comp) {
if ($row['BeingServiced'] == $unco and $row['ReadyForCollection'] == $unco) {
(etc.)
}
}
测试一次,然后测试其他条件更有效:
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
if ($row['InGarage'] == $comp) {
if ($row['BeingServiced'] == $comp) {
if ($row['ReadyForCollection'] == $unco) {
echo "Vehicle is being serviced<br />";
}
elseif ($row['ReadyForCollection'] == $comp) {
echo "Vehicle is ready for collection<br />";
}
}
elseif ($row['BeingServiced'] == $unco and $row['ReadyForCollection'] == $unco) {
echo "Vehicle is in Garage<br />";
}
}
}
if($row['InGarage'] == $comp) {
if ($row['BeingServiced'] == $unco and $row['ReadyForCollection'] == $unco) {
(etc.)
}
}
除了非常粗鲁之外,马克是对的。这可以通过DO和if语句来实现。当我使用if语句时,不会打印任何内容,而与循环一样,它会打印大量的时间。。。当我使用if语句时,我会将我的新代码放在问题的主体中,不会打印任何内容;因为您将所有内容都放在循环体之外:)在更新的代码中,您甚至在到达
if()
语句之前就关闭了循环。@皮特我不希望它循环,这是我的问题,我更喜欢嵌套,因为它使代码更容易(对我来说)阅读。如果你喜欢排长队,那就用另一种方法。此外,原始代码在每个if
上测试第一个条件,$row['ingarge']==$comp
。只需要测试一次,还是没什么。。。我设置了一个回音,以确保连接已建立is@ialarmedalien当找不到SQLSRV行时,如何添加另一个if语句,使其成为另一行?我试过了,但没有成功。你可以将整个东西嵌套在一个“if-else”循环中--if($row=sqlsrv\u-fetch\u-array($stmt,sqlsrv\u-fetch\u-ASSOC)){……代码遍历行…}否则{echo“没有从数据库检索到数据!”}
。在这段代码之前,你是否做过错误检查以确保连接正常?是的,当连接建立时,我有一个回音要打印。现在很好用!