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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)