gpt4 book ai didi

php - mysql使用php安全快速的选择和插入

转载 作者:可可西里 更新时间:2023-11-01 08:46:25 24 4
gpt4 key购买 nike

我有一个简单的表,逻辑是在插入新行之前,我应该从该表中获取一列。让我解释一下:

表格

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

您会看到,每个 groupId 的键都像自动递增一样递增。当 id 为 2 的组想要添加一个新的笔记时,他应该知道最后一个键。找到它后,php 将 +1 添加到最后一个键并插入一个新行。我这样做如下:

$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);

这个方法对我很有效,但我担心从表中获取最后一个键时会发生冲突吗?因为,同时,10 个具有相同 groupId 的用户可以添加新行。 php 可以同时为组 ID 为 2 的 3 个用户获取相同的 key 吗?

有什么快速安全的方法吗?

最佳答案

您可以使用 MyISAM 通过 AUTO_INCREMENT 执行此操作。

来自 MySQL Docs :

For MyISAM and BDB tables you can specify AUTO_INCREMENT on a secondary column in a multiple-column index. ... This is useful when you want to put data into ordered groups.

否则,您应该使用类似 SELECT MAX(key) + 1 FROM table WHERE groupID = 1 的子查询在插入查询中设置值并读回该值。

关于php - mysql使用php安全快速的选择和插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27380044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com