php - 根据日期和用户 ID 检查记录是否存在,如果不存在则创建它,如果存在则更新它 - 同时添加值而不是替换它们

标签 php mysql sql

我正在尝试使用 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 个步骤来完成:

  1. 在表中创建一个名为 day 的列,其中仅包含日期(不含时间)。

  2. dayuser_id 上创建类型为 unique 的索引。

  3. 如果该用户和当天的条目已存在,请在插入中使用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/

相关文章:

sql - 在 SQL 中使用触发器的非空约束

php - 将 SQL 查询传递给 Google map 的 JS 数组

php - 使用用户名而不是电子邮件的 JWTAuth 身份验证

php - 在哪里转义字符串来防止mysql注入(inject)?

mysqldump 未创建创建数据库语法

sql - 通过 PostgreSQL 为数据库中的列设置默认值

javascript - 使用相应的记录内容更新 jquery 对话框表单

php - 我怎样才能避免在 PHP 的 While 循环中使用 MySQL 查询

php - 搜索已登录用户的名称

php - Mysql 将引号存储为 '