Mohammad Eskandari
Mohammad Eskandari

Reputation: 141

Why php api is returning null after code rewrited with bind_result?

I'm using this PHP API for android app to get token to send notification base on server and user[Phone]. problem is i'm getting error in app and only this part of my api is getting errors. which error is

<br />
<b>Notice</b>:  Undefined variable: token in <b>/home/meskand1/public_html/pasargad-drinkshop/db_functions.php</b> on line <b>390</b><br />
null

I've commented line 390 and function code below.

Code was working fine with get_Result & fetch_assoc, but because online host didn't supported mysqlnd, i've forced to change this. can anyone explain where is mistake happen and why? in tutorial with get_Result instructor returned $token, now with my code this is getting errors.

Here's the code in function:

public function getToken($phone,$isServerToken){
   $stmt = $this->conn->prepare("SELECT phone, token, isServerToken FROM `token` WHERE phone=? AND isServerToken=?") or die ($this->conn->error);
   $stmt->bind_param("ss",$phone,$isServerToken);
   $result = $stmt->execute();
   $stmt->bind_result($a,$b,$c);
   while ($stmt->fetch()){
       $token[] = ['phone' => $a, 'token' => $b, 'isServerToken' => $c];
   }
   $stmt->close();
   return $token; // => This is line 390
}

Call

if(isset($_POST['phone']) && isset($_POST['isServerToken'])){
   $userPhone = $_POST['phone'];
   $isServerToken = $_POST['isServerToken'];

   $token = $db->getToken(urlencode($userPhone),$isServerToken);

   echo json_encode($token);

} else {
   $response = "Required parameter (phone , isServerToken) is missing!";
   echo json_encode($response);
}

Upvotes: 1

Views: 336

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

If your SQL doesn't match any data, $token is undefined as it is only ever set in the loop. You should at least initialise it before the loop just in case...

$stmt->bind_result($a,$b,$c);
$token = array();    // Initialise
while ($stmt->fetch())
{
    $token[] = ['phone' => $a, 'token' => $b, 'isServerToken' => $c];
}
$stmt->close();
return $token; 

Upvotes: 1

Related Questions