请告诉我,如何解决以下问题。
javascript.js 从 Givemedata.php 获取数据,后者从数据库中选择数据并锁定所选行,以使其对于其他查询不可见,如
从 data_table LIMIT 1 中选择 * 进行更新
然后 javascript.js 处理数据并将其中一些数据发送回 storemydata.php,然后 storemydata.php 将删除锁定的行。
问题是如何告诉数据库该行应保持锁定,即使 Givemedata.php 已结束,直到 storemydata.php 想要删除锁定的行,并且是否有任何类型的句柄可以存储在 $_SESSION 中告诉?
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());
}
?>