0

Inside MySQL, There is a Users table with three columns like this:

id (int) name (char) wallet_balance (int) hasMembership (tinyint)
1 user1 125 0
2 user2 23 0
3 user3 986 0

Let's suppose the price of membership is 100.

Here is the current scenario:

  1. Inside the android app, The user clicked on the buy button.
  2. Send the user id to the server using Retrofit.
  3. In the server, Get the wallet balance from the database using the user id.
  4. If the wallet balance was 100 and more then remove 100 from his wallet and update the fourth column to 1.
  5. If the wallet balance was 99 and below then I'll execute this code echo "8012";
  6. Inside the android, Inside the onResponse method, I'll check if the body contains the 8012 number, If yes I'll tell the user he does not has enough balance, Otherwise, I'll tell the user he bought it successfully.

Is there any way to send the 8012 number as an error instead of printing it because Retrofit handles it as a successful result?

I want when I send the 8012 number, Execute the onFailure method and check from the number inside the onFailure method instead of the onResponse method.

The main question: Is there any way to send the 8012 number as an error instead of printing it using PHP?

I hope everything is clear.

Taha Sami
  • 1,565
  • 1
  • 16
  • 43
  • Just send as error code with `exit('8012');`. – Markus Zeller Jun 22 '22 at 09:48
  • You could use [http_response_code()](https://www.php.net/manual/en/function.http-response-code). 8012 could be your very own [response code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status). – KIKO Software Jun 22 '22 at 09:53
  • @KIKOSoftware But I want to create custom status codes. 8012 means you don't have enough money. 6200 means you cannot follow yourself. etc... – Taha Sami Jun 22 '22 at 09:58

1 Answers1

1

you may set a response header. All types of request evaluate 20x (e.g 200,201,202,...) as successful response. so if anything printing in the content that was not one of other errors like 500 or 403 or ... it will be proceed as 200 family! so you may use http_response_code() function like this, and then use any content you want in body of response:

http_response_code(8112)

EDITED:

in the other hand you may save your result from db in a variable and create a switch case and then set the header for each type of status you want :

<?php
  switch ($balance){
     case 99:
        $status = 8112;
        $msg = "not enough money";
        break;
     case 100:
         $status = 8110;
         $msg ="some other message";
         break;
          .
          .
          .
         default:
         $status = 200;
         $msg ="successful";
     }

$response = [
     'code' => $status,
     'message' => $msg
];
http_response_code($status);
echo json_encode($response);
Milad Elyasi
  • 789
  • 4
  • 12