[英]MySQL specific number of entries
Hello i have got a Mysql table that i fill within a php script. 您好,我有一个Mysql表,我在一个php脚本中填写。 In this script i check if the number of entries of a specific type has reached the maximum to inform the customer.
在此脚本中,我检查特定类型的条目数是否已达到最大数量,以通知客户。 If the number of entries is less i let him insert a new entry into my table.
如果条目数较少,我让他在表中插入一个新条目。 The table looks like this
桌子看起来像这样
--------------------
Date | Type
--------------------
Tuesday 13:00 | Car
And the php script that checks looks like this 和检查的PHP脚本看起来像这样
<?php
$sql = $conn->prepare("SELECT count(*) FROM Table WHERE Date='Tuesday 13:00' AND Type='Car'");
$sql ->execute();
$sql_rows = $sql->fetchColumn();
if ($sql_rows > 20){
echo "All entries for this type has been filled please choose another to continue";
}else{
$insert = $conn->prepare("INSERT INTO Table VALUES('Tuesday 13:00', 'Car')");
$insert -> execute();
}
?>
My problem now is that if 100 people access this php script at the same moment will the php script allow exactly 19 people to insert themselves 'Tuesday 13:00','Car' into the database or more and how could i prevent that without creating inconvenience to the clients? 我现在的问题是,如果100个人同时访问此php脚本,该php脚本将允许恰好19个人将自己的“星期二13:00”,“汽车”插入数据库或更多,我如何才能避免这种情况而无需创建给客户带来不便?
Use a transaction to ensure that both queries work with the same snapshot of the table. 使用事务来确保两个查询都使用表的相同快照。 The transaction will lock the table so that other people will wait.
该事务将锁定表,以便其他人等待。 Put
$conn->startTransaction()
before the first SELECT
query, add a FOR UPDATE
clause to the query, and $conn->commit()
after the INSERT
. 将
$conn->startTransaction()
放在第一个SELECT
查询之前,将FOR UPDATE
子句添加到查询中,并将$conn->commit()
放在INSERT
。
You must be using InnoDB, not MyISAM, for transactions to be effective. 您必须使用InnoDB,而不是MyISAM,交易才能生效。
<?php
$sql = $conn->prepare("SELECT count(*) FROM Table
WHERE Date='Tuesday 13:00' AND Type='Car'
FOR UPDATE");
$conn->startTransaction();
$sql ->execute();
$sql_rows = $sql->fetchColumn();
if ($sql_rows > 20){
echo "All entries for this type has been filled please choose another to continue";
}else{
$insert = $conn->prepare("INSERT INTO Table VALUES('Tuesday 13:00', 'Car')");
$insert -> execute();
}
$conn->commit();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.