InnoDB 如何使用 script1.php 锁定数据库行并使用 script2.php 删除它

问题描述 投票:0回答:1

请告诉我,如何解决以下问题。

javascript.js 从 Givemedata.php 获取数据,后者从数据库中选择数据并锁定所选行,以使其对于其他查询不可见,如

从 data_table LIMIT 1 中选择 * 进行更新

然后 javascript.js 处理数据并将其中一些数据发送回 storemydata.php,然后 storemydata.php 将删除锁定的行。

问题是如何告诉数据库该行应保持锁定,即使 Givemedata.php 已结束,直到 storemydata.php 想要删除锁定的行,并且是否有任何类型的句柄可以存储在 $_SESSION 中告诉?

php locking innodb delete-row
1个回答
0
投票
 In   givemedata.php:

    <?php
session_start();
include 'db_connection.php'; // Make sure you have a db_connection.php that sets up your PDO connection

try {
    $conn->beginTransaction(); // Start a new transaction

    // Lock the row for update
    $stmt = $conn->prepare("SELECT * FROM data_table LIMIT 1 FOR UPDATE");
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($row) {
        // Store the locked row's identifier in the session
        $_SESSION['locked_row_id'] = $row['id'];
    }

    // Send the data to the client
    echo json_encode($row);

    // Commit the transaction
    $conn->commit();
} catch (Exception $e) {
    $conn->rollBack();
    echo "Failed: " . $e->getMessage();
}
?>

In storemydata.php:
    <?php
session_start();
include 'db_connection.php'; // Ensure you have your PDO connection here

try {
    if (isset($_SESSION['locked_row_id'])) {
        $lockedRowId = $_SESSION['locked_row_id'];

        // Start a new transaction
        $conn->beginTransaction();

        // Delete the locked row
        $stmt = $conn->prepare("DELETE FROM data_table WHERE id = :id");
        $stmt->bindParam(':id', $lockedRowId, PDO::PARAM_INT);
        $stmt->execute();

        // Commit the transaction
        $conn->commit();

        // Clear the locked row id from session
        unset($_SESSION['locked_row_id']);
    } else {
        throw new Exception("No row locked.");
    }

    echo json_encode(['status' => 'success']);
} catch (Exception $e) {
    $conn->rollBack();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>

in db_connection.php:
    <?php
$host = '127.0.0.1';
$db = 'your_database';
$user = 'your_username';
$pass = 'your_password';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $conn = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>
© www.soinside.com 2019 - 2024. All rights reserved.