简体   繁体   English

计算行数然后更新-PHP Mysql

[英]Count number of rows then update - Php Mysql

I'm trying to count the rows from a table with date timestamp and then update with total rows created in the last 24 hours: 我正在尝试使用日期时间戳计算表中的行,然后使用最近24小时内创建的总行进行更新:

Here is function code 这是功能代码

function limitexchnage($eid) {
  global $db;
  $query = $db->query("SELECT * FROM exchanges WHERE uid='$eid' and created less than 24 hour ");
    while($row = $query->fetch_assoc()) {
        $update = $db->query("UPDATE users SET maxechange='$query->num_rows' WHERE id='$eid'");
   }  }

I need someone to help me finds timestamps in the last 24 hours and fix this code. 我需要有人帮助我找到最近24小时内的时间戳并修复此代码。

将此条件放在WHERE (Date_Time = getdate())子句中WHERE (Date_Time = getdate())

function limitexchnage() {
global $db;
$check = $db->query("SELECT * FROM exchanges WHERE `created` > (UNIX_TIMESTAMP(NOW()) - 86400) AND `uid` = '$eid'");
        $update = $db->query("UPDATE users SET maxechange='$check->num_rows' WHERE id='$eid'"); }

try this query 试试这个查询

"SELECT * FROM exchanges WHERE uid='$eid' and date > DATE_SUB(CURDATE(), INTERVAL 1 DAY);"

same condition in update too. 相同的条件也更新。 this returns date with value within last 24 hrs 这会返回日期,最后24小时内的值

You can actually combine these into a single query: 您实际上可以将它们组合成一个查询:

function limitexchnage($eid) {
    global $db;
    $query = $db->query("UPDATE users SET maxechange=(SELECT COUNT(uid) FROM exchanges WHERE uid='$eid' AND created < NOW() AND created > DATE_SUB(NOW(), INTERVAL 1 DAY)) WHERE id='$eid'");
}

You should swap the COUNT(uid) part to use the primary index of exchanges table. 您应该交换COUNT(uid)部分以使用exchanges表的主索引。 Remember to escape/sanitize $eid when using directly in the query! 在查询中直接使用时,请记住对$eid进行转义/ $eid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM