1

我是 php 新手,我把我的代码弄乱了一点。我将不胜感激任何帮助。

$sqltest="SELECT MaId,Amount FROM table1";
$stmttest = sqlsrv_query( $conn, $sqltest);
if( $stmttest === false) {
    die( print_r( sqlsrv_errors(), true) );
}
while($test = sqlsrv_fetch_array( $stmttest, SQLSRV_FETCH_ASSOC)){ //fetch array
$combined[] = array($test['MaId']=>$test['Amount']); //pass the first column values as array keys
}
$loop=0;
foreach ($combined as $key => $value) {
    foreach ($value as $msid => $msamount) {
       while($msid!==25) {
          $loop += $msamount;
       }
    }
 }   

我试图将 id 不等于 25 的所有金额相加,但我陷入了无限循环。你能解释一下出了什么问题吗?

4

2 回答 2

2

改变:

while($msid!==25) {

到:

if ($msid!==25) {

我必须同意马克贝克上面评论),如果你可以在数据库中做到这一点,你应该:

$sqltest = 'SELECT SUM(Amount) AS Amount FROM table1 WHERE MaId <> 25';
$stmttest = sqlsrv_query($conn, $sqltest);

if ($stmttest === false) {
    die(print_r(sqlsrv_errors(), true));
}

$amount = 0;

if ($row = sqlsrv_fetch_array($stmttest, SQLSRV_FETCH_ASSOC)) {
    $amount = $row['Amount'];
}
于 2013-09-23T21:22:08.897 回答
2

while你应该是一个if

if($msid!==25) {
   $loop += $msamount;
}
于 2013-09-23T21:22:31.577 回答