我正在 php 中设置一个事件,并将其保存到 mysql。稍后,我想更新事件,但为了知道需要更新哪个事件,我使用创建时间。
但是,如果多个事件在同一秒开始,如果我们有很多用户,我可能会遇到问题。我的解决方案是检查开始时间和用户编号,我认为它们应该足够独特。这个可以吗?有更好的方法吗?
首先,创建事件时:
$starttime = time();
mysql_query("INSERT INTO events (userid, starttime)
VALUES ('$userid', '$starttime')");
稍后,更新事件:
mysql_query("UPDATE events
SET newdata='$newdata'
WHERE starttime='$starttime'
AND userid='$userid'");
最佳答案
糟糕的方法。只需在该表上放置一个 auto_incrementing 主键 ID 字段,这将为您提供一个有保证的唯一非重复值,您可以唯一地标识一行,而不必担心重叠/冲突:
ALTER TABLE events ADD id int unsigned primary key auto_increment;
您可以在插入查询后自动检索该值:
$sql = "INSERT ...";
$result = mysql_query($sql) or die(mysql_error());
$new_id = mysql_insert_id(); // see here: http://us2.php.net/manual/en/function.mysql-insert-id.php
... other stuff...
$sql = "UPDATE ... WHERE id = $new_id;":
$result = mysql_query($sql) or die(mysql_error());
关于php - 为 mysql 行使用标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8775157/