简体   繁体   English

如何防止同时执行REST API的多次执行?

[英]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] ... 我如何才能防止同时执行多个REST API ...我有一个具有多个MySQL数据库操作的rest API ...当同时从多个设备调用API时,这将在我的MySQL操作中造成多个问题API [PHP文件] ...

How i can fix that ? 我该如何解决? any suggestions ? 有什么建议么 ? consider.. i am a beginner 考虑..我是一个初学者

My REST API code: 我的REST API代码:

<?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. 但这是不寻常的模式)DB中的所有事务都遵循ACID原则。 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. 另外,我注意到您没有对输入进行清理,这需要进行SQL注入。 Consider addressing that as well, use this link to guide you: How can I prevent SQL injection in PHP? 也考虑解决该问题,请使用此链接指导您: 如何防止PHP中的SQL注入?

In any case, your SQL transaction should look like this: 无论如何,您的SQL事务应如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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