How can I add hours and minutes?


What I'm looking for is a button that when I click on it, I add the hours and minutes of each record and its total appears in a field, this script is only doing the query of the hours but I do not know how to add them.

echo "<body>";
$id = $_POST['id'];

$conexion =  mysqli_connect("localhost", "root","admin123","database");

$query = "SELECT servicio_No, movil, despacho, salida, llegada_Origen, salida_Origen, llegada_Destino1, salida_Destino1, llegada_Destino2, salida_Destino2, disponible FROM servicio WHERE servicio_No = ?";

/*Prepara la setencia SQl para su ejecucion*/
if ($stmt = mysqli_prepare($conexion, $query)) {

    /*Agrega variables a una sentencia preparada como parametros*/
    /* ligar parámetros para marcadores */
    /*IMPORTANTE: Si id no es numérico en la base de datos, cambia la i por una s*/
    mysqli_stmt_bind_param($stmt, "i", $id);

    /* Ejecuta una consulta preparada */

    /*Se transfiere los  resultados de la ultima consulta*/

    /* Vincula las variables a una setencia preparada para el almacenamineto de result */
    $stmt->bind_result($servicio_No, $movil, $despacho, $salida, $llegada_Origen, $salida_Origen, $llegada_Destino1, $salida_Destino1, $llegada_Destino2, $salida_Destino2, $disponible);

    while ($stmt->fetch()) {
        echo "
    <body class='body'>
    <h1>Modificar tiempos</h1><br><br>
    <form method='POST' action = 'modificandoTiempos.php'>
    <label>Numero del servicio</label><br>
    <input type='int' name='servicio_No' value='".$servicio_No."'>


    <input type='int' name='movil' value='".$movil."'>



        <input type='text' name='despacho' value='".$despacho."' placeholder='1.Despacho'>
        <input type='text' name='salida' value='".$salida."' placeholder='2.Salida'>
        <input type='text' name='llegada_Origen' value='".$llegada_Origen."'  placeholder='3.Llegada Origen'></br>
        <br><input type='text' name='salida_Origen' value='".$salida_Origen."' placeholder='4.Salida Origen'>
        <input type='text' name='llegada_Destino1' value='".$llegada_Destino1."' placeholder='5.Llegada Destino 1'>
        <input type='text' name='salida_Destino1' value='".$salida_Destino1."' placeholder='6.Salida Destino 1'></br>
        <br><input type='text' name='llegada_Destino2' value='".$llegada_Destino2."' placeholder='7.Llegada Destino 2'>
        <input type='text' name='salida_Destino2' value='".$salida_Destino2."' placeholder='8.Salida Destino 2'>
        <input type='text' name='disponible' value='".$disponible."' placeholder='9.Disponible'>


         <input type='submit' name='' value='Actualizar'>

         <input type='button' value='Volver de donde viniste!' onclick='history.back(-2)' class='submit'/> 

asked by Cristian Antonio Trujillo Gris 28.05.2018 в 15:06

2 answers


Let's expose a practical case to list the records of the database as well as generate a total of one of the fields of type TIME through PHP.

Suppose we have in the database a table like the following:


| id | user    | tiempo   |
|  1 |       1 | 10:22:51 |
|  2 |       1 | 05:21:09 |
|  3 |       2 | 01:02:15 |
|  4 |       3 | 23:10:01 |

We could use the function TIME_TO_SEC of MySQL so that we can return the time in seconds and thus have a value according to which we can do PHP operations, example:

SELECT, a.user, TIME_TO_SEC(a.tiempo) tiempo_segundos
FROM 'docs' a;

| id | user | tiempo_segundos |
|  1 |    1 |           37371 |
|  2 |    1 |           19269 |
|  3 |    2 |            3735 |
|  4 |    3 |           83401 |

If we want to work the total time in seconds we could do a SUM directly in Mysql, example:

SELECT SUM(TIME_TO_SEC(a.tiempo)) total_segundos 
FROM 'docs' a;

| total_segundos |
|         143776 |

In php if we want to show the records and add at the same time we can do the following for example, commented code:


First we create a function to go from seconds to days, hours, minutes, seconds and format, then we simply add the times in seconds for once we have the total of seconds to pass the value to the function.

// Declarmos una función para formatear de segundos a días, horas, minutos, segundos
function seg_a_dhms($seg) {
    $d = floor($seg / 86400);
    $h = floor(($seg - ($d * 86400)) / 3600);
    $m = floor(($seg - ($d * 86400) - ($h * 3600)) / 60);
    $s = $seg % 60;
    return "$d días, $h horas, $m minutos, $s segundos";

// conexión
$conexion =  mysqli_connect("localhost", "user","pass","database");
// query
$query = "SELECT, a.user, TIME_TO_SEC(a.tiempo) tiempo_segundos, a.tiempo
FROM 'docs' a;";

// preparar consulta
if ($stmt = $conexion->prepare($query)) {
    // ejecutar consulta
    //recuperar resultados
    // Vincular resultados a variables
    $stmt->bind_result($id, $user, $tiempo_segundos, $tiempo);

    // Declaramos una variable para sumar el tiempo
    $total_tiempo_sec = 0; 
    while ($stmt->fetch()) {
        // mostramos lo que necesitemos
        echo 'El registro '.$id.' del usuario '.$user.' tiene un tiempo de '.$tiempo;
        // vamos acumolando la suma de los tiempos en segundos
        $total_tiempo_sec += $tiempo_segundos;

    // una vez que finalice el while solo nos falta dar formato 
    // al total de tiempo con la función que declaramos al principio
    echo seg_a_dhms($total_tiempo_sec); // 1 Días, 15 horas, 56 minutos, 16 segundos
answered by 28.05.2018 / 21:34

If I have understood correctly what you want, you can get the difference minutes in each step in the query itself in mysql , for example assuming that your departure and arrival fields are type datetime :

$query = "SELECT servicio_No, movil, despacho, salida, llegada_Origen, salida_Origen, llegada_Destino1, salida_Destino1, llegada_Destino2, salida_Destino2, disponible 
, TIMESTAMPDIFF(MINUTE, 'salida', 'llegada_Origen') as tiempo1
, TIMESTAMPDIFF(MINUTE, 'salida_Origen', 'llegada_Destino1') as tiempo2
FROM servicio WHERE servicio_No = ?"

Then you just have to add the minutes of the sections you want and convert them to hours by dividing the total of minutes by 60. In this way you have the calculation directly from the query and you can show it at the same moment you fill in the data. I hope it serves you.

answered by 28.05.2018 в 16:08