[英]mysql select and insert safely and quickly with php
I have a simple table, the logic is that before inserting a new row, I should fetch one column from that table. 我有一个简单的表,逻辑是在插入新行之前,我应该从该表中获取一列。 Let me explain:
让我解释:
table
id key groupId Note
1 00001 1 abd
2 00002 1 aasdas
3 00003 1 aasdas
4 00001 2 q2eqwd
5 00002 2 qwdvvd
6 00003 2 qwrqw
7 00004 2 qwdqdqw
You see, key increases like Auto Increment for each groupId. 你看,每个groupId的自动递增键增加。 When group with id 2, wants to add a new note, he should know last key.
当id为2的组想要添加新音符时,他应该知道最后一个键。 After finding it, php addes +1 to last key and inserts a new row.
找到它之后,php将+1添加到最后一个键并插入一个新行。 I do it like below:
我这样做如下:
$groupId = 2; //for example
$note = $_POST['note'];
$select = $db -> prepare("SELECT key FROM table where groupId = :groupId ORDER BY id DESC limit 1");
$select -> bindValue(":groupId", $groupId, PDO::PARAM_INT);
$select -> execute();
$fetch = $select -> fetch(PDO::FETCH_ASSOC);
$lastKey = $fetch['key']+1;
$insert = "INSERT INTO table (key, groupId, note) VALUES(:key, :groupId, :note)";
$ins = $db -> prepare($insert);
$insert -> bindValue(":key", $lastKey, PDO::PARAM_INT);
$insert -> bindValue(":groupId", $groupId, PDO::PARAM_INT);
$insert -> bindValue(":note", $note, PDO::PARAM_STR);
This method works good for me, but I am afraid of is here will be any conflict while fetching last key from table? 这种方法对我有用,但我担心在从表中获取最后一个键时会出现任何冲突吗? Because, at the same time, 10 user with same groupId can add a new row.
因为,同时,具有相同groupId的10个用户可以添加新行。 May php fetch same key to 3 users with group ID 2 at the same time?
php可以同时为3个用户组ID ID 2获取相同的密钥吗?
Is there any quickly and safely way? 有没有快速安全的方式?
You can do this with AUTO_INCREMENT
using MyISAM. 您可以使用MyISAM使用
AUTO_INCREMENT
执行此操作。
From MySQL Docs : 来自MySQL Docs :
For MyISAM and BDB tables you can specify AUTO_INCREMENT on a secondary column in a multiple-column index.
对于MyISAM和BDB表,您可以在多列索引中的辅助列上指定AUTO_INCREMENT。 ... This is useful when you want to put data into ordered groups.
...当您想要将数据放入有序组时,这非常有用。
Otherwise, you should set the value in your insert query with a subquery like SELECT MAX(key) + 1 FROM table WHERE groupID = 1
and read back the value. 否则,您应该使用
SELECT MAX(key) + 1 FROM table WHERE groupID = 1
等子查询设置插入查询中的值,并回读该值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.