出于某种原因,下面的while循环永远不会触发。 所有这些都在课堂内。
$code = $this->get_postal_state_no('Western Cape');
private function get_postal_state_no($psn)
{
$sql = "
SELECT
no
FROM
ct_state
WHERE
name LIKE('".$psn."');";
$stmt = sqlsrv_query($this->conn1, $sql);
// This statement is not false, so the error handling does not happen, this is expected.
if($stmt === FALSE)
{
if(($errors = sqlsrv_errors()) != NULL)
{
foreach($errors as $error)
{
$sqlstate = $error['SQLSTATE'];
$code = $error['code'];
$sqlmessage = $error['message'];
}
}
$msg = 'Error in $stmt in get_postal_state_no() method.';
$this->do_error_log($error_msg, $sqlstate, $code, $sqlmessage, $msg, __LINE__, __FILE__, __FUNCTION__, __CLASS__, __METHOD__);
sqlsrv_free_stmt($stmt);
}
//This loop is never entered. This is not expected.
while($obj = sqlsrv_fetch_object($stmt))
{
echo "I am here now";
break;
if(!empty($obj->no) && $obj->no != '')
{
echo "Hello, I exist";
break;
// This break never happens
return $obj->no;
}
else
{
echo "Hello, I don't exist";
break;
// This break never happens
$code = $this->sp_aa_iud_ct_state($psn);
return $code;
}
sqlsrv_free_stmt($stmt);
}
}
有谁知道为什么?我正在使用php_sqlserv驱动程序。 SQL Server Profiler shopws查询第一部分执行。
由于
Ĵ
答案 0 :(得分:2)
查看sqlsrv_fetch_object的文档页面,它说明了返回值:
成功时返回一个对象,如果没有更多行要返回则返回NULL,如果发生错误或指定的类不存在则返回FALSE。
我怀疑该功能正在返回NULL
或FALSE
,但原因有点不清楚。尝试在while
循环上方添加此内容并查看输出结果:
$obj = sqlsrv_fetch_object($stmt)
var_dump($obj);
die;
while($obj = sqlsrv_fetch_object($stmt))
{ // ...
另一个有用的调试技巧是转储查询,然后将其复制/粘贴到您的DBMS系统中,并直接针对您的数据库运行您在代码中执行的查询,以查看是否实际返回了任何结果:
$sql = "
SELECT
no
FROM
ct_state
WHERE
name LIKE('".$psn."');";
var_dump($sql);