我的代码中出现一个PHP错误未定义变量。我正在使用PDO对输出进行json_encode。当我测试我的代码时,我得到那个错误。将来如何解决并避免这种情况?我的代码结构可以吗?还是我需要对其进行改进以避免这种问题
未定义变量:ar
$sql = $conn->prepare("SELECT UserID, UsrPassword, ContactID, UserTypeID, UserStatus, ClientUpdate, ServerUpdate, Deleted FROM tblUsers WHERE ContactID = :contactid AND ServerUpdate > :lastchecked AND Deleted != :deleted", $cursor);
$sql->bindValue(":contactid", $ContactID);
$sql->bindValue(":lastchecked", $LastChecked);
$sql->bindValue(":deleted", 1);
if($sql->execute()){
$count = $sql->rowCount();
if($count > 0){
while ($row = $sql->fetch()) {
$decr = CryptRC4(FromHexDump($row['UsrPassword']), $key);
if($row['ServerUpdate'] > $row['ClientUpdate']){
$lupdate = date("Y-m-d h:i:s", strtotime($row['ServerUpdate']));
}
else{
$lupdate = date("Y-m-d h:i:s", strtotime($row['ClientUpdate']));
}
$ar[] = array(
'UserID' => $row['UserID'],
'UsrPassword' => $decr,
'ContactID' => $row['ContactID'],
'UserTypeID' => $row['UserTypeID'],
'UserStatus' => $row['UserStatus'],
'Deleted' => $row['Deleted'],
'LastUpdated' => $lupdate
);
}
}
}
else{
$ar[] = array(
"Message" => $sql->errorInfo(),
"sql" => $sql
);
}
print json_encode($ar);
答案 0 :(得分:1)
您需要在if语句之前将$ ar变量声明为数组,以便不限制变量的范围,并且可以在If else之外访问此变量。
$sql = $conn->prepare("SELECT UserID, UsrPassword, ContactID, UserTypeID, UserStatus, ClientUpdate, ServerUpdate, Deleted FROM tblUsers WHERE ContactID = :contactid AND ServerUpdate > :lastchecked AND Deleted != :deleted", $cursor);
$sql->bindValue(":contactid", $ContactID);
$sql->bindValue(":lastchecked", $LastChecked);
$sql->bindValue(":deleted", 1);
$ar = array();
if(){
// You code goes here
}
else{
// You code goes here
}
print_r($ar);
答案 1 :(得分:0)
似乎没有满足if($count > 0){
条件,请在此之前声明ar,希望这会有所帮助
$sql = $conn->prepare("SELECT UserID, UsrPassword, ContactID, UserTypeID, UserStatus, ClientUpdate, ServerUpdate, Deleted FROM tblUsers WHERE ContactID = :contactid AND ServerUpdate > :lastchecked AND Deleted != :deleted", $cursor);
$sql->bindValue(":contactid", $ContactID);
$sql->bindValue(":lastchecked", $LastChecked);
$sql->bindValue(":deleted", 1);
$ar = array();
if($sql->execute()){
$count = $sql->rowCount();
if($count > 0){
while ($row = $sql->fetch()) {
$decr = CryptRC4(FromHexDump($row['UsrPassword']), $key);
if($row['ServerUpdate'] > $row['ClientUpdate']){
$lupdate = date("Y-m-d h:i:s", strtotime($row['ServerUpdate']));
}
else{
$lupdate = date("Y-m-d h:i:s", strtotime($row['ClientUpdate']));
}
$ar[] = array(
'UserID' => $row['UserID'],
'UsrPassword' => $decr,
'ContactID' => $row['ContactID'],
'UserTypeID' => $row['UserTypeID'],
'UserStatus' => $row['UserStatus'],
'Deleted' => $row['Deleted'],
'LastUpdated' => $lupdate
);
}
}
}
else{
$ar[] = array(
"Message" => $sql->errorInfo(),
"sql" => $sql
);
}
print_r(json_encode($ar));