我在表中总共有 42 条记录。问题是我的一个专栏,它指示休假类型,称为$empType
。在该表的列中,$empType
的第 24 条记录称为"病假"但由于 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。
<?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.
}
}
正如
Jon 指出的那样,你的 if 需要在 while 内部,但你也从不定义$status所以 if 无论它在哪里都不会运行
您
正在循环遍历该while
中的每一行数据,但您有一个 if
语句,其中包含一个 var 的条件,该条件在 while
循环之外的每个循环中重新声明......
您需要在while
内安装if
:
$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;