dongzhang6677 2016-09-22 07:12
浏览 83
已采纳

如何在SQL中添加TIME格式字段并使用PHP正确显示它?

The SQL field that I try to add is TIME format.

My table looks like this: table example

The code that I use looks something like this:

<code>

$sql = mysql_query("SELECT sec_to_time(sum(durata)) as durata FROM invoiri WHERE inginer= '" . $inginer."' and data between  '" . $data1."' and  '" . $data2."'");                             
                $assoc = mysql_fetch_array($sql);
                    echo "Total time by ".$inginer." in period (".$data1.")-(".$data2.") is: ".$assoc[durata]." hours";}}
</code>

And the output that I get is " 05:33:20 " when it should be " 02:00 "

  • 写回答

1条回答 默认 最新

  • dqm7854 2016-09-22 08:50
    关注

    You almost have the right solution there. The problem is that the durata column is also a TIME column, and SUM() works on integers not TIME.

    To get the correct result you can use:

    $sql = mysql_query('SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(`durata`))) AS `durata` FROM `invoiri` WHERE inginer= "' . $inginer. '" AND `data` BETWEEN "' . $data1 . '" AND "' . $data2 . '"';
    $assoc = mysql_fetch_array($sql);
    echo 'Total time by ' . $inginer . ' in period (' . $data1 . ')-(' . $data2 . ') is: ' . $assoc[durata] . ' hours';
    

    Also, a few of other things that you can improve about your code:

    1. Stop using the MySQL extension for PHP. It has been deprecated since PHP 5.5 and completely removed in PHP 7. Instead have a look at MySQLi or PDO.

    2. Don't use " for strings where you don't use string interpolation. You can see how I replaced all of your " (double quote) with ' (single quote). String processing is faster if you use just single quotes as PHP isn't trying to find something to interpolate every time.

    3. Try to have your MySQL code more organized and use backticks for column names, and capitalize all of the MySQL syntax. I have modified your code as an example.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀