PHP if-else тел как выполняет - PullRequest
0 голосов
/ 18 мая 2018

Я новичок в PHP, и у меня есть этот код, где части if и else выполняются в одном и том же «прогоне».Я знаю, что это логически невозможно, но это то, что я получаю.

Вот мой PHP-код:

<?php

require_once 'create_request_form.php';

$db = new create_request_form();

// json response array
$response = array("error" => FALSE);

if (isset($_POST['rqTitle']) && isset($_POST['rqMname']) && isset($_POST['rqUname']) && isset($_POST['rqBranch']) && isset($_POST['rqText']) && isset($_POST['rqMinPrice']) && isset($_POST['rqMaxPrice']) && isset($_POST['rqImage']) && isset($_POST['rqCategory']) && isset($_POST['rqDateTime'])) {

    // receiving the post params
    $rqTitle = $_POST['rqTitle'];
    $rqMname = $_POST['rqMname'];
    $rqUname = $_POST['rqUname'];
    $rqBranch = $_POST['rqBranch'];
    $rqText = $_POST['rqText'];
    $rqMinPrice = $_POST['rqMinPrice'];
    $rqMaxPrice = $_POST['rqMaxPrice'];
    $rqImage = $_POST['rqImage'];
    $rqCategory = $_POST['rqCategory'];
    $rqDateTime = $_POST['rqDateTime'];


    // check if there is a request  with the same title
    if ($db->checkReqTitle($rqTitle)) {
        // Request already exists
        $response["error"] = TRUE;
        $response["error_msg"] = "Request already exists with the title: " . $rqTitle;
        echo json_encode($response);
    } else {
        // create a new request
        $request = $db->StoreReqInfo($rqTitle, $rqMname, $rqUname, $rqBranch, $rqText, $rqMinPrice, $rqMaxPrice, $rqImage, $rqCategory, $rqDateTime);

        if ($request) {
            // request stored successfully
            $response["error"] = FALSE;
            $response["request"]["rqTitle"] = $request["rqTitle"];
            $response["request"]["rqMname"] = $request["rqMname"];
            $response["request"]["rqUname"] = $request["rqUname"];
            $response["request"]["rqBranch"] = $request["rqBranch"];
            $response["request"]["rqText"] = $request["rqText"];
            $response["request"]["rqMinPrice"] = $request["rqMinPrice"];
            $response["request"]["rqMaxPrice"] = $request["rqMaxPrice"];
            $response["request"]["rqImage"] = $request["rqImage"];
            $response["request"]["rqCategory"] = $request["rqCategory"];
            $response["request"]["rqDateTime"] = $request["rqDateTime"];

            echo json_encode($response);

        } else {
            // request failed to store
            $response["error"] = TRUE; 
            $response["error_msg"] = "An error occurred while creating the request. Please try again.";
            echo json_encode($response);
        }
     }
} else {
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameter is missing!";
    echo json_encode($response);
}
?>

Требуемое поведение (хранение данных в базе данных) все работает хорошо, но ответ $ , который я получаю, - этоСтрока ошибки, которую я назначил, когда заголовок запроса уже существует вместо отформатированного в JSON массива хранимого запроса (оба , если и иначе тела выполняются, но я получаю результат if body в качестве ответа).

Снимок экрана $ response с использованием Postman для отправки запроса: enter image description here

Скриншот из моегоSamsung Galaxy Note 3: enter image description here

Я также использую Galaxy Note 4 для тестирования, и он просто показывает пустое сообщение Toast и не запускает намерение (неперейти к начальному экрану).

Пока единственное возможное объяснение состоит в том, что сценарий выполняется дважды, однако я не могу найти нигде, который вызывал бы его во второй раз.

Это java-код, отвечающий за отправку запроса с необходимыми параметрами в скрипт php выше.

 private void storeRequest(final String rTitle, final String rMname, final String rUname,
                          final String rBranch, final String rText,  final String rMinPrice,
                          final String rMaxPrice, final String imagePath, final String rCategory) {

    // Tag used to cancel the request
    String cancel_req_tag = "request";

    //A progress dialog message to let the user know they are being registered
    progressDialog.setMessage("Please wait while we add your request...");
    showDialog();

    //creating a StringRequest to send the registration info to the script
    // at the server for processing
    StringRequest strReq = new StringRequest(Request.Method.POST,
            URL_FOR_REQUEST, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            Log.d(TAG, "Request Response: " + response.toString());
            hideDialog();

            try { //json objects must be surrounded by try catch statement
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                if (!error) { // error is set to false, meaning no error

                    // Launch home activity
                    Intent intent = new Intent(CreateRequestActivity.this, HomeActivity.class);
                    startActivity(intent);
                    finish();

                } else {

                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(CreateRequestActivity.this, errorMsg, Toast.LENGTH_LONG).show();
                }



            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Error: " + error.getMessage());
            Toast.makeText(CreateRequestActivity.this,
                    error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("rqTitle", rTitle);
            params.put("rqText", rText);
            params.put("rqMname", rMname);
            params.put("rqUname", rUname);
            params.put("rqBranch", rBranch);
            params.put("rqMinPrice", rMinPrice);
            params.put("rqMaxPrice", rMaxPrice);
            params.put("rqImage", imagePath);
            params.put("rqCategory", rCategory);
            params.put("rqDateTime", DateFormat.getDateTimeInstance().format(new Date()));
            return params;
        }
    };
    // Adding request to request queue
    AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}

Есть идеи?

Заранее спасибо!

1 Ответ

0 голосов
/ 18 мая 2018

Так получается, что проблема проистекает из кода Java, а не PHP (плохой PHP; P).Точнее, у запросов Volley есть проблема с тайм-аутами запросов, особенно при отправке запросов методом POST.

Итак, для меня сработало добавление этой строки непосредственно перед добавлением запроса в очередь:

strReq.setRetryPolicy(new DefaultRetryPolicy(0, -1, 0));

* Замените strReq на ваш запрос название.По сути, эта строка предотвращает отправку повторного запроса залпом, когда первый запрос занимает слишком много времени.

Исходный ответ с дополнительными данными:

Класс hasAttemptRemaining () класса DefaultRetryPolicy.class выглядит следующим образом:

protected boolean hasAttemptRemaining () {return this.mCurrentRetryCount<= this.mMaxNumRetries;} Из того, что я вижу, установка maxNumRetries в 0 все равно сделает это возвращение true, если он еще не сделал попытку. </p>

Я исправил это с помощью

request.setRetryPolicy (newDefaultRetryPolicy (0, -1, 0);

Источник: Android Volley делает 2 запроса к серверу, когда для политики повтора установлено значение 0

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...