PHP中的子查询将数据提取到Excel

我有两个表格:

biometrics - records in and out of employees emp - employee records 

在我的生物识别表中,有一个状态。

 0 - if the employee went out 1 - if the employee went in 

员工可以在一天中拥有多个0和1的状态,因为您在rest时也可以进入计时和超时状态。 所以状态可以是这样的:

 time_created status 9:00 1 --- time in 12:00 0 --- time out for break 13:00 1 --- time in again after break 18:00 0 --- time out 

所以员工可以有多个rest时间。

我已经有了这个正确的查询,但这是问题。 我正在制作一个logging所有rest的节目。 当我将其提取到Excel时,“超时”列和“timediff”(显示员工在rest时间花费的总小时数和分钟数的列)列中的问题未显示。 这两列是子查询的产物。

这是我的代码:

  if(isset($_POST['timediff'])){ header("Content-type: text/csv; charset=UTF-8"); header('Content-Disposition: attachment; filename=Export_Date.csv'); $con = mysql_connect("localhost", "root"); if(!$con){ echo "Error connection"; } $select_db = mysql_select_db('sample', $con); if(!$select_db){ echo "Error to select database"; } mysql_set_charset("utf8", $con); $myquery2 = mysql_query("select g.empno, emp.emp_fname, emp.emp_fname, emp.position, emp.office , g.date_created, min(g.time_created), g.timeout, timediff(g.timeout, min(g.time_created)) FROM ( select id_biometrics, empno,date_created, time_created, ( SELECT min(s.time_created) FROM biometrics s WHERE s.status like '0' AND s.time_created > base.time_created AND s.empno= base.empno AND s.date_created = base.date_created ORDER BY s.time_created ASC) as timeout from biometrics base where base.status like '1' ) g, emp WHERE emp.empno = g.empno AND NOT (g.timeout = (SELECT min(time_created) FROM biometrics where status like '1')) GROUP BY g.empno, g.timeout ORDER BY g.date_created;"); //While loop to fetch the records $contents = "empno,emp_fname,emp_lname,position,office,date_created,timeout,timein,timediff\n"; while($row = mysql_fetch_array($myquery2)) { $contents.=$row['empno'].","; $contents.=$row['emp_fname'].","; $contents.=$row['emp_lname'].","; $contents.=$row['position'].","; $contents.=$row['office'].","; $contents.=$row['date_created'].","; $contents.=$row['min(g.time_created)'].","; $contents.=$row['g.timeout'].","; $contents.=$row['timediff(g.timeout, min(g.time_created)']."\n"; } $contents_final = chr(255).chr(254).mb_convert_encoding($contents, "UTF-16LE","UTF-8"); print $contents_final; } ?> 

“时间”正在显示。 只有最后两列:“超时”(g.timeout)和“timediff”没有显示。 我不知道什么是错的,因为在MySQL Workbench中,这个查询是完美的。

您需要在您的SELECT语句中别名您的列:

 SELECT ... timediff(g.timeout, min(g.time_created)) AS mytimediff FROM ... 

该列可以作为mytimediff访问。

可能还有另外一种方法可以不用别名来读取它:暂时的,在循环中尝试添加print_r($row) ,看看这个列是如何被引用的,而不需要显式的SQL别名。 这就是说,我认为这是更好的一个适当的别名。

最后,你可能知道mysql库已经被弃用了。 如果可能,请将您的应用程序转换为使用PDO / MySQL或MySQLi。

完成! 哈哈。 我用这种方法打印它,

  while($row = mysql_fetch_array($myquery2)) { $contents.=$row[0].","; $contents.=$row[1].","; $contents.=$row[2].","; $contents.=$row[3].","; $contents.=$row[4].","; $contents.=$row[5].","; $contents.=$row[6].","; $contents.=$row[7].","; $contents.=$row[8]."\n"; } 

感谢print_r($ row)的halfer。它告诉我,每一列都在一个数组中,因此我通过提供索引来打印它。 :D:D