简体   繁体   中英

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:

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.

将此条件放在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

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. Remember to escape/sanitize $eid when using directly in the query!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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