简体   繁体   English

PHP MYSQL:即时选择+插入

[英]PHP MYSQL: instant select + insert

I need to pull from MYSQL a value , than change forward the value and insert in to the mysql. 我需要从MYSQL中获取一个值,而不是向前更改该值并插入到mysql中。

for example : 例如 :

$str = mysql_fetch_assoc(mysql_query('SELECT `str_id` FROM `ids` ORDER BY `num_id` DESC LIMIT 1 ')); // = aaa
$str = $str++; // aaa -> aab
// than check if "aab" key already exist
// if not , insert as key as "aab"

as for this algorithm there is a risk that this script runs from the two sides of the globe and two unique keys will be sign as "aab".. 对于此算法,此脚本有可能从地球的两侧运行,并且两个唯一的密钥将被标记为“ aab”。

how can i do this without risk of sign this unique key two times? 我该怎么做而又没有两次签名此唯一密钥的风险?

If you set up your database so that the column is unique, the MySQL table will not allow you to add the same value twice. 如果您设置数据库以使该列是唯一的,则MySQL表将不允许您两次添加相同的值。 You can then check the result of the transaction to ensure that it succeeded. 然后,您可以检查交易结果以确保交易成功。

From your example it looks like you just want an incremented unique key. 从您的示例看来,您只需要一个递增的唯一键。 You should use an integer for this, which can automatically increment when you insert a new row. 您应该为此使用一个整数,当您插入新行时,它可以自动递增。 If you want it to be in string form just perform some basic math on it. 如果您希望它为字符串形式,只需对其执行一些基本数学运算即可。 ie

1 = a
2 = b
...
27 = aa
28 = ab

This is assuming you don't already have a primary key on your table, in which case I don't understand why you need the string in that form. 这是假设您的表上没有主键,在这种情况下,我不明白您为什么需要这种形式的字符串。 Hopefully this helps, and I apologize if I misunderstood the question. 希望这会有所帮助,如果我误解了这个问题,我深表歉意。

When using MySQL-InnoDB you should use Transactions (Provided by MySQLi and PDO) for that cause. 使用MySQL-InnoDB时,应使用Transaction(由MySQLi和PDO提供)解决该问题。 MyISAM does not support it. MyISAM不支持它。

Here is the manual about transactions in PDO: http://php.net/manual/en/pdo.transactions.php 这是有关PDO中交易的手册: http : //php.net/manual/en/pdo.transactions.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM