将时间插入数据库不会保存正确的格式

问题描述 投票:0回答:1

我正在尝试像这样在数据库中插入时间:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['customer']) && isset($_POST['time']) && isset($_POST['often'])) {
    
    $customer_id = $_POST['customer'];                        
    $day = (int)date('w');                                       
    $time_input = $_POST['time'];                           
    $often = $_POST['often'];                         

    
    $stmt = $conn->prepare("INSERT INTO visits (customer_id, day, time, often) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("isii", $customer_id, $day, $time_input, $often);

    if ($stmt->execute()) {
       // Redirect to the same page
        header("Location: ".$_SERVER['REQUEST_URI']);
        exit();
    } else {
        // Insert failed
        echo "Error adding new visit: " . $conn->error;
    }

    // Close the prepared statement
    $stmt->close();
}
?>

<input type="time" class="form-control" name="time" id="time" required>

如果我们输入 08:00 - 数据库条目为 00:00:08

可能出了什么问题?

我尝试过:

// Extract hours and minutes from the time input
list($hours, $minutes) = explode(':', $_POST['time']);

// Format the time as HH:ii:00 (hours, minutes, seconds)
$time_input = sprintf('%02d:%02d:00', $hours, $minutes);

和:

$time_input = date('H:i:s', strtotime($_POST['time']));

但是结果是完全一样的。

我们的表格描述是:

Field   Type    Null    Key     Default     Extra   
id  int     NO  PRI     NULL    auto_increment
customer_id     int     YES     MUL     NULL    
day     int     YES         NULL    
time    time    YES         NULL    
often   int     YES         1   
php mysql input time mysqli
1个回答
0
投票

此问题的解决方案是将绑定参数从“i”整数更改为“s”字符串。

$stmt = $conn->prepare("INSERT INTO visits (customer_id, day, time, often) VALUES (?, ?, ?, ?)");
$stmt->bind_param("issi", $customer_id, $day, $time_input, $often);
© www.soinside.com 2019 - 2024. All rights reserved.