Select 来自 table 的值并使用它来更新相同 table 的字段

Select a value from a table and use it to update a field of the same table

我正在获取一些 12 小时制的时间数据,我想将 12 小时制转换为 24 小时制 hour.This 是我编写的使用 mysqli 的脚本。

<?php
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "qplat";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "select the_time from r_data where transaction_type = 'send'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    $id = 8980;
    while($row = $result->fetch_assoc()) {
    $new_id = $id++;
        $new_time = $row["the_time"];
        echo "the time is: " . $row["the_time"].'<br/>';
        $time = date("Hi", strtotime("$new_time"));
        $sql2 = "update r_data set 24_hour_time = '$time' where transaction_type = 'send' and id = $new_id";
        $conn->query($sql2);
    }
} else {
    echo "0 results";
}
$conn->close();
?> 

脚本更新列 24_hour_time 一次,仅忽略所有其他行。

这可以使用一个 table 来完成,还是我必须插入另一个 table 然后将数据移回?

您可以像这样使用 codeigniter 解决您遇到的问题

public function up(){
    $query = $this->db->query("select id,the_time from r_data where transaction_type = 'send'");
    foreach ($query->result() as $row)
    {
    $id = $row->id;
    $new_time = $row->the_time;
    $time = date("Hi", strtotime("$new_time"));
    $data = array(
               '24_hour_time' => $time
            );

    $this->db->where('id', $id);
    $this->db->update('r_data', $data); 
    }
    }