我正在尝试使用 sql 脚本 (MySql) 创建一个 php 页面,该脚本将检查用户是否已经添加了当天的记录。如果他们还没有,我想创造这个记录。如果有,我想用新信息更新记录。
例如:
1) no record found... add the following info
user_id number
-------- ------
00001 1
2) database now looks like this
index date user_id number
----- ----- -------- -------
1 2015-03-23 11:41:51 00001 1
3. php page is called again by the same user the same day month and year just a few minutes later with the following data:
user_id number
-------- ------
00001 5
4) database should now looks like this
index date user_id number
----- ----- -------- -------
1 2015-03-23 11:41:51 00001 6 <---notice the numbers are added
5) if the user calls the php page the following day I want it to create a new record.
我不确定这是否可以仅使用 sql 来完成,或者是否还需要添加 php 代码,任何帮助将不胜感激,谢谢。
------------------编辑----------------------------------------
我用来添加新记录的代码。
$query = mysqli_query($connection, "INSERT INTO myTable(user_id, number)
VALUES(00001,1)");
我不确定如何检查包含日期/时间/年份以及 user_id 的记录,或者如何添加数字
(如上面的示例所示)。
最佳答案
您可以通过这 3 个步骤来完成:
在表中创建一个名为
day
的列,其中仅包含日期(不含时间)。在
day
和user_id
上创建类型为unique
的索引。如果该用户和当天的条目已存在,请在插入中使用
on重复键
语句来触发更新:INSERT INTO 表 (a,b,c) 值 (1,2,3) 重复 key 更新 c=c+1;
取自:http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
关于php - 根据日期和用户 ID 检查记录是否存在,如果不存在则创建它,如果存在则更新它 - 同时添加值而不是替换它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29221597/