2 回答
TA贡献1824条经验 获得超5个赞
考虑以下几点 1) 您希望多个管理员编辑不同的产品 2) 您不希望多个管理员编辑同一产品
3)在您的代码中,您将产品保存为单个表。在一个真实的电子商务网站产品信息被拆分成几个表格
要实现这一点,您必须设置应用程序范围的 mysql 锁
mysql> select get_lock('product_id_12345', 5);
+---------------------------------+
| get_lock('product_id_12345', 5) |
+---------------------------------+
| 1 |
+---------------------------------+
1 row in set (0.00 sec)
上面的代码使用 product_id 设置了一个锁,如果其他一些连接尝试使用相同的 product_id 获取锁,你将得到 0 作为响应 - 表明其他一些用户正在更新相同的 product_id
mysql>
mysql> select IS_FREE_LOCK('product_id_12345');
+----------------------------------+
| IS_FREE_LOCK('product_id_12345') |
+----------------------------------+
| 0 |
+----------------------------------+
1 row in set (0.00 sec)
mysql>
mysql> select IS_USED_LOCK('product_id_12345');
+----------------------------------+
| IS_USED_LOCK('product_id_12345') |
+----------------------------------+
| 46 |
+----------------------------------+
1 row in set (0.00 sec)
mysql>
mysql> select connection_id();
+-----------------+
| connection_id() |
+-----------------+
| 46 |
+-----------------+
1 row in set (0.00 sec)
示例算法
<?php
ini_set('display_errors', 1);
function updateProduct() {
$user = 'root';
$pass = 'xxx';
$DB = 'test';
$host = 'localhost';
try
{
$conn = new mysqli($host, $user, $pass, $DB);
$data['productId'] = 'product_id_12345';
$data['productName'] = 'test';
$data['productDesc'] = 'testing';
$isLockFree = 'select IS_USED_LOCK("'.$data['productId'].'") ';
$isLockFreeResult = mysqli_query($conn, $isLockFree);
$row=mysqli_fetch_row($isLockFreeResult);
if(empty($row[0]))
{
$lock = 'select get_lock("'.$data['productId'].'")';
$result = mysqli_query($conn, $lock);
echo 'lock established';
$query = "UPDATE products
SET product_name='".$data['productName']."',
product_desc='".$data['productDesc']."',
price=".$data['price']."
WHERE
product_id=".$data['productId'];
$result = mysqli_query($conn, $query);
if ($result == false)
{
throw new Exception('Failed to execute: '. $query . 'Error: '. mysqli_error($conn));
}
}
else
{
echo 'sorry! could not lock. somebody is updating the product info';
}
}
finally
{
mysqli_close($conn);
}
}
updateProduct();
?>
- 2 回答
- 0 关注
- 100 浏览
添加回答
举报