0

我的表中共有 42 条记录。问题是我的专栏之一,它指示休假类型,是 call $empType。在我那张表的列中,第 24 条记录$empType称为“病假”,但由于 while 循环,$empType只显示第 42 条记录,因此整个 if 语句不起作用。

我不希望它只显示第 24 条记录,因为我知道odbc_fetch_row它也能正常工作,但我希望它一直循环并捕获每一行的所有数据。

$conn=odbc_connect("employee","","") or die (odbc_errormsg());

$sql1="SELECT * FROM employee WHERE Status='Pending'";
$rs1=odbc_exec($conn,$sql1);
while (odbc_fetch_row($rs1))
{
$leaveID=odbc_result($rs1,"Leave ID");
$empID=odbc_result($rs1,"empID");
$empType=odbc_result($rs1,"TypeOfLeave");
}

if ($status == "Approved" && $empType == "Medical Leave")
{
my code
}

echo $empType;

谁能帮我解决这个问题?我真的需要完成这件事。

我正在使用 Microsoft 访问数据库 ODBC。

4

3 回答 3

1
<?php
$conn = odbc_connect("employee","","") or die (odbc_errormsg());

$sql1 = "SELECT * FROM employee WHERE Status='Pending'";
$rs1 = odbc_exec($conn,$sql1);

while(odbc_fetch_row($rs1)) {
    $leaveID=odbc_result($rs1,"Leave ID");
    $empID=odbc_result($rs1,"empID");
    $empType=odbc_result($rs1,"TypeOfLeave");
    $status = odbc_result($rs1,"Status"); // added this.


    // moved to the while loop.
    if( $empType === 'Medical Leave' && $status === 'Approved' ) {
        // your code.
    }
}

此外,PHP 的 ODBC API 看起来很吓人,所有的 odbc_fetch_row、odbc_result 都在进行。也许为此使用 PDO 是个好主意?这样,代码将如下所示:

<?php
$dbh = new Pdo( 'odbc:MSSQLServer', 'username', 'password' );

$results = $dbh->query( 'SELECT * FROM employee', PDO::FETCH_ASSOC );

foreach( $results as $result ) {
    if( $result['TypeOfLeave'] === 'Medical Leave' && $result['Status'] === 'Approved' ) {
        // your code here.
    }
}

我没有尝试将 PDO 与 ODBC 一起使用,所以我不熟悉错误,但据我所知;除了您正在使用的 API 之外,任何其他 API 都是一种改进。

编辑:如果您想稍后使用所有行(用于循环等),这是一个不错的选择:

<?php
$conn = odbc_connect("employee","","") or die (odbc_errormsg());

$sql1 = "SELECT * FROM employee WHERE Status='Pending'";
$rs1 = odbc_exec($conn,$sql1);

$rows = array( );

while(odbc_fetch_row($rs1)) {
    $rows[] = array(
        'leave ID' => odbc_result( $rs1, 'Leave ID' ),
        'empID' => odbc_result( $rs1, 'empID' ),
        'empType' => odbc_result( $rs1, 'empType' ),
        'status' => odbc_result( $rs1, 'Status' ),
    );
}

// $rows now contains *all* rows, which you can loop over later.

// some more code here.

foreach( $rows as $row ) {
    if( $row['status'] === 'Approved' && 'empType' === 'Medical Leave' ) {
        // your code here.
    }
}
于 2012-05-10T10:01:25.697 回答
0

正如乔恩指出的那样,你的 if 需要在 while 内,但你也从来没有定义 $status 所以无论它在哪里 if 都不会运行

于 2012-05-10T09:47:47.257 回答
0

您正在遍历其中的每一行数据,while但您有一个if语句包含一个 var 的条件,该条件在循环外 while 的每个循环中重新声明while...

你需要有if内部while

$conn=odbc_connect("employee","","") or die (odbc_errormsg());

$sql1="SELECT * FROM employee WHERE Status='Pending'";
$rs1=odbc_exec($conn,$sql1);
while (odbc_fetch_row($rs1))
{
$leaveID=odbc_result($rs1,"Leave ID");
$empID=odbc_result($rs1,"empID");
$empType=odbc_result($rs1,"TypeOfLeave");

if ($status == "Approved" && $empType == "Medical Leave")
{
my code
}//end of if

}//end of while

echo $empType;
于 2012-05-10T09:54:40.050 回答