php - 为 mysql 行使用标识符

标签 php mysql

我正在 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/

相关文章:

mysql - SQL语句 "for each state with more than 20 members whose first name start with “D”。”?

php - 将可变数量的变量传递给 PHP 中的类

php - 从表中生成唯一的配对——一个 "Fixture"

C#/SQL : 'System.Data.Objects.ObjectSet<DatabaseName.TableName> does not contain a definition for ' Local'

php - mysql按空格拆分搜索字符串并插入查询

mysql - .toList() 返回异常

php - [0-9]+ 和 [0-9]++ 有什么区别?

php - 通知表设计?

PHP Nginx error_log 被截断

PHP 堆栈偶尔显示空白页