I am getting a PHP error undefined variable in my code. I am using PDO to json_encode the output. When I test my code I am getting that error. How can I fix and avoid this in the future? Is my code structure ok? or do I need to improve it in order to avoid this problem
Undefined variable: 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);
$ar = [];before the first if-statement. The problem is whenif($count > 0)evaluates as false (the query doesn't return anything), then$ardoesn't get defined.