简体   繁体   中英

How Can I Prevent Multiple Execution of REST API in same time?

how i can prevent multiple execution of a REST API in same time... i have a rest API with several MySQL database operation... when API call from multiple devices on same time ,that will make several issues in my MySQL operations in rest API [PHP file] ...

How i can fix that ? any suggestions ? consider.. i am a beginner

My REST API code:

<?php


    $receipt = $_POST["receipt"];
    $maxselect = $_POST["maxselect"];
    $user = $_POST["user"];
    $pass = $_POST["pass"];
    $trans = $_POST["trans"];
    include("dbConnect.php");

    $result=mysqli_query($conn,"SELECT emp_pass FROM emp WHERE emp_name ='$user'");

    $affected = mysqli_affected_rows($conn);
    if ($affected > 0) {
  #USER DETAILS MATCH
    while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
        $password = $row['emp_pass'];

    }
    }


    if(strcmp($pass, $password) !== 0)  {
        $response = false;
        echo json_encode($response);#encoding RESPONSE into a JSON and returning.
        mysqli_close($conn);
        exit();
    } 


    // $randomtime =rand(0,2000000);
    // usleep($randomtime);

    $check=mysqli_query($conn,"CALL saveReceipt('$maxselect','$receipt','$trans')");




    $response = true;
    echo json_encode($response);#encoding RESPONSE into a JSON and returning.
    mysqli_close($conn);
    exit();



    ?>

You can create lock-file and write into it flag in the beginning and erase flag(or nulled) in the ending of your critical section. But it's unusual pattern) All transactions in DB are follows the ACID principles. All they are Isolated)

I agree with what Renat said about it being a strange pattern. DB transaction is the way to go to handle your race condition. Also, I noticed you are not sanitizing your inputs, which is subject to SQL injection. Consider addressing that as well, use this link to guide you: How can I prevent SQL injection in PHP?

In any case, your SQL transaction should look like this:

-- select to see if your receipt exists before proceeding
START TRANSACTION;
CALL saveReceipt('%s','%s','%s');
COMMIT;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM