dongtie0929 2018-10-25 13:41
浏览 72
已采纳

选择date = NOW()的行?

I am trying to create a table that logs steps depending on date and the user id. But when I run my code, it happens that I get duplicate rows if a user logs their steps several times a day. I can't have a date with a unique key because that would cause all other users unable to log steps if a any other user has logged steps the same day. So my point is that I want to remove the option of having duplicate rows where user id and date is identical. I have two tables

Table a and table b, and I will refer to them as something.a and something.b

I have a problem with returning a valid row when using $entry = "SELECT * FROM table.a WHERE userid.a = '$user_id.b' AND date=NOW()"

I want to use it as a conditional to decide to either UPDATE or INSERT INTO table.a. I have user_id.b from an previous query which works as it is, so I will leave that as it is for now.

Here is how I query the database:

$entry_result = mysqli_query($conn, $entry);

Which is used here:

if (mysqli_num_rows($entry_result) > 0){
    $conn->query("UPDATE steplogger SET steps='$steps' WHERE userid='$user_id' AND date=NOW()");
} else {
    $conn->query("UPDATE users SET totalsteps = totalsteps + ('$steps') WHERE username = '$user'");
    $conn->query("INSERT INTO steplogger (steps, userid, date) VALUES ('$steps', '$user_id', NOW())");
}

Any thoughts on what I am doing wrong?

PS. When I echo $entry_result I get a mysqli object.

  • 写回答

2条回答 默认 最新

  • dongshan4878 2018-10-25 13:44
    关注

    As you said :

    I want to remove the option of having duplicate rows where user id and date

    The best way is to create an UNIQUE index on user_id and date, this way you won't be able to insert two rows with same user_id and date.

    With an UNIQUE index, you can use INSERT...ON DUPLICATE KEY UPDATE that will do what you want : you will insert a new row (new user_id + date) and if a row already exists with the same user_id and date, you will update the row.

    Here is the documentation : https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法