PHP Server Handling Using Android

Jyotishgher Astrology
By -
0

PHP Server Handling Using Android

The php://input stream in PHP is a read-only stream that allows you to access the raw data from the request body. This is particularly useful when you need to handle raw data from an HTTP request, such as when building RESTful APIs, processing form submissions, or handling file uploads.

PHP Server Handling Using Android


Let suppose you want to make an Api and calling into android App.The code for PHP page is:

<?php
include_once($_SERVER['DOCUMENT_ROOT'] . "/cmms/utils/header.php");

$response = [];

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Retrieve and validate inputs
$input = json_decode(file_get_contents("php://input"), true);

$STAGE_CD   = $input['STAGE_CD'] ?? null;

if (!$COACH_TYPE || !$PROD_YR || !$SHELL_NO || !$GRP_CD || !$STAGE_CD) {
    echo json_encode([
        "status" => 400,
        "message" => "Missing required parameters."
    ]);
    exit;
}

// Ensure database connection exists
if (!isset($conn)) {
    echo json_encode([
        "status" => 500,
        "message" => "Database connection is not defined."
    ]);
    exit;
}

try {
    // Prepare SQL
    $query = "
        select MAX(TXN_ID) as TXN_ID from fstatus where  stage_cd =:STAGE_CD ";


    $stmt = oci_parse($conn, $query);
    if (!$stmt) {
        throw new Exception("Failed to prepare the SQL statement.");
    }

    // Bind parameters

    oci_bind_by_name($stmt, ":STAGE_CD", $STAGE_CD);
    // Execute statement
    if (!oci_execute($stmt)) {
        $error = oci_error($stmt);
        throw new Exception("Database execution error: " . $error['message']);
    }

    // Fetch results
    $rows = [];
    while ($r = oci_fetch_assoc($stmt)) {
        $rows[] = array_map('htmlentities', $r);
    }

    echo json_encode([
        "status" => 200,
        "message" => "Success",
        "data" => $rows
    ]);
} catch (Exception $e) {
    echo json_encode([
        "status" => 500,
        "message" => "Internal Server Error",
        "error" => $e->getMessage()
    ]);
}
?>

Whose POSTMAN SAMPLE IS:

{
    "status"200,
    "message""Success",
    "data": [
        {
            "TXN_ID""2507"
        }
    ]
}

So for Calling $input = json_decode(file_get_contents("php://input"), true);
 Now make changes in the Android Java Code as Suppose a Method is:

private void CheckTXN_ID(String coachType, String selectedShellNo, String selectedProdYr, String stageCd) {
if (selectedShellNo.equals("Select Shell No") || selectedShellNo.isEmpty()) {
Log.w("CheckTXN_ID", "Skipped TXN_ID check due to invalid shell number");
return;
}

Log.d("CheckTXN_ID", "Calling with: coachType=" + coachType + ", shellNo=" + selectedShellNo + ", prodYr=" + selectedProdYr + ", stageCd=" + stageCd);

final ProgressDialog loading = ProgressDialog.show(this, "Stage Check", "Please wait...", false, false);

// Prepare JSON request body
JSONObject params = new JSONObject();
try {

params.put("STAGE_CD", stageCd);
} catch (JSONException e) {
loading.dismiss();
e.printStackTrace();
Toast.makeText(this, "Error building request", Toast.LENGTH_SHORT).show();
return;
}

JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, TXN_ID_URL, params,
response -> {
loading.dismiss();
Log.d("TXN_ID_RESPONSE", response.toString());

try {
int success = response.getInt("status");

if (success == 200) {
JSONArray dataArray = response.getJSONArray("data");
if (dataArray.length() > 0) {
JSONObject data = dataArray.getJSONObject(0);
TXN_ID = data.optString("TXN_ID", "0");
Log.d("Parsed-TXN_ID", "TXN_ID: " + TXN_ID);
} else {
TXN_ID = "0";
Toast.makeText(this, "No TXN_ID found", Toast.LENGTH_SHORT).show();
}
} else {
TXN_ID = "0";
Toast.makeText(this, "No record found", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
TXN_ID = "0";
e.printStackTrace();
Toast.makeText(this, "Error parsing TXN_ID JSON", Toast.LENGTH_SHORT).show();
}
},
error -> {
loading.dismiss();
TXN_ID = "0";
Log.e("TXN QUERY failed", error.toString());
Toast.makeText(this, "TXN QUERY failed: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
);

RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonRequest);
}
Tags:

Post a Comment

0Comments

Post a Comment (0)