我需要在我的mysql数据库活动中传递09.03.2014和12.03.2014:
SELECT * FROM activity;
ID timestamp_day name details
1 1394319600 Meeting Meeting with Ann about job
2 1394406000 Travel Go to New York
3 1394492400 Work Do some work...
4 1394578800 Vacation Prepare all necessary stuff
5 1394319600 Car repair Go to store to buy new parts for car
我需要获得的是一个用于创建datatable.net的JSON数据表:
Datum | Name
----------+-----
Sunday |
09/03 |
----------+-----
Monday |
10/03 |
----------+-----
Tuesday |
11/03 |
----------+-----
Wednesday |
12/03 |
----------+-----
我尝试做什么:
PHP:
$dateString = '09.03.2014';
$startDate = new DateTime($dateString);
$period = new DateInterval('P1M');
$endDate = clone $startDate;
$endDate->add($period);
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($startDate, $interval ,$endDate);
$i=1;
foreach($daterange as $date){
$temp = array();
// the following line will be used to slice the Pie chart
$temp['ID'] = $i;
$dejt = $date->format("l") . PHP_EOL;
$temp['datum'] = '<strong>'.$dejt.'</strong></br>'.$date->format("d/m") . PHP_EOL;
$rs1 = $db->prepare('SELECT name FROM activity WHERE timestamp=:ts');
$rs1->bindParam(':ts', $timestamp);
$rs1->execute();
$naz = $rs1->fetchColumn();
if ($naz != false) {
$temp['name'] = $naz;
} else {
$temp['vrsta'] = '';
}
$output['data'][] = $temp;
$i++;
$jsonTable = json_encode($output);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo $jsonTable;
和JQuery:
$('#example').dataTable( {
"ajax": "table1.php",
"columns": [
{ "data": "ID" },
{ "data": "datum" },
{ "data": "name" },
], etc.
我的代码工作正常,但是当我有相同的timestamp_day值时,我也会多次查询数据库,然后我才第一次......
所以你看到我用每个日期的问题打了mysql数据库。我想创造其他方式来做到这一点?如何使用JOIN mysql函数看起来如此...?此外,您可以看到我的ID 1和ID 5具有相同的时间戳,因此我需要将这些行的名称放在一个单元格中,并为此数据创建单独的HTML。
答案 0 :(得分:1)
不熟悉datatable.net,我只会向您展示一个通过一次数据库调用获取结果的选项。必要时进行调整。
$rs1 = $db->prepare('SELECT * FROM activity;');
$rs1->execute();
$rows = $rs1->fetchAll();
$daterange = new DatePeriod($startDate, $interval ,$endDate);
$activities = array();
if (count($rows) > 0)
{
foreach ($rows as $row)
{
$activities[$row['timestamp_day']][] = $row['name'];
}
foreach($daterange as $date)
{
$formattedData = $data //format your date to timestamp here
if (!array_key_exists($formattedDate, $activities))
{
$activities[$formattedDate] = array();
}
}
}
为您提供具有以下格式的数组:
$activities = array(
[1394319600] => array('Meeting', 'Car repair')
[1394406000] => array('Travel')
[1394492400] => array('Work')
[1394578800] => array('Vacation')
)