从表中选择一个值并使用它来更新同一个表的字段

时间:2015-01-24 16:12:09

标签: php mysqli

我正在以12小时的格式获取一些时间数据,我想将其从12小时转换为24小时。这是我编写的使用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一次,只留下所有其他行。

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

1 个答案:

答案 0 :(得分:1)

你可以解决使用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); 
    }
    }