到期时间结束时如何更新数据

时间:2019-07-10 04:10:11

标签: php codeigniter

我已经用Codeigniter构建了一个应用程序,并且想做cron工作并使用MySQL

我有一个表格“ order”,并具有这样的字段

order_id | order_expired_date
001      | 2018-11-12 10:03:33

我有这样的表“ order_payment”,

order_id | op_status
001      | pending

这两个表中有很多字段,但仅包括与该问题有关的字段

我有来自php的代码,但没有在模型codeigniter中

$result = mysql_query('UPDATE `'order_payment'`
    SET op_status='expired' 
    WHERE
    (UNIX_TIMESTAMP( now( ) ) - `order_expired_date`));

问题是如何在到期时间到期后将order_payment表中的状态更改为过期?

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码,您需要根据需要修改代码。

<?php

    $servername = "xyz";
    $username = "xyz";
    $password = "xyz";
    $dbname = "xyz";
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);

    $sql = "SELECT *,o.`order_id` as `oid` FROM `order` as o,`order_payment` as op WHERE o.`order_id`=op.`order_id` AND op.`op_status`='paid'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {

                  $today = date('Y-m-d');
                  $expDt = date('Y-m-d',strtotime($row['order_expired_date']));

                  if($today==$expDt){
                      $updCltSql = "UPDATE `order_payment` SET `op_status`='expired' WHERE `order_id`='".$row['oid']."'";
                      $conn->query($updCltSql);                        
                  }             
        }
    }

    $conn->close();
?>

我们总是更喜欢core-php文件作为cron-job。.

答案 1 :(得分:-1)

经过大量研究,这是我想出的-希望对您有所帮助。在您的示例中,我认为您不需要在表名order_payment周围加上单引号,除非这是CodeIgniter特有的。

$orderID = mysql_query("SELECT order_id FROM order");  // Get order IDs of order table, assuming it has the same list of order IDs as the order_payment table
$order_ids = array();   // Put in array
while ($row = mysql_fetch_array($orderID)) {
   $order_ids[] = $row['order_id'];
}

foreach ($order_ids as $order_id) {   // Iterating through order_id's of array in order to read same index/row number from both tables
  $expirationDate = mysql_query("SELECT order_expired_date FROM order WHERE order_id='$order_id'");
  $expire = date('M j Y g:i A', $expirationDate);   // Converting MySQL timestamp to correct format for strtotime
  $today = strtotime("now");
  if($today >= $expire)   // If past the expiration date
      mysql_query("UPDATE order_payment SET op_status='expired' WHERE order_id='$order_id'");
}