将带有唯一行号的自动增量列添加到现有表中
ALTER TABLE mytable ADD idnum INT NOT NULL AUTO_INCREMENT;
(或在新表中添加字段
CREATE TABLE mytable (
idnum INT NOT NULL AUTO_INCREMENT,
... )
并将idnum设置为PRIMARY KEY
.
这样所有行都有一个由 MySQL 自动创建的唯一编号。要插入一行,请将字段设置为null,MySQL 会自动设置数字
INSERT INTO mytable (idnum, ...) VALUES (null, ...);
请注意,您可以检索 MySQL 自动设置的idnum,这要归功于 PHP API,例如mysqli(请参阅此页面),
$lastid = $mysqli->insert_id(); // $mysqli being the mysqli object
然后要更新一个值,你必须存储在某个地方(最好在会话中而不是在页面上[因为在这种情况下用户可以修改它 - 除非没关系])
// Modify field form
...SELECT idnum,nhours FROM mytable WHERE thedate = ...
$_SESSION['idnum'] = $row['idnum'];
...
// Display form ...
// Form processing
// Check first if SESSION has an idnum (an other parameters) in case the user hacked the page and submit a "special" form ...
/// Then
$res=mysql_query("UPDATE study SET nhours='$hours' WHERE idnum=" . $_SESSION['idnum']);