Last active
August 29, 2015 13:56
-
-
Save hanafiah/8916872 to your computer and use it in GitHub Desktop.
generate pivot table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
try { | |
$db = new PDO('mysql:host=127.0.0.1;dbname=sampledb;charset=utf8', 'root', ''); | |
} catch (PDOException $e) { | |
echo $e->getMessage(); | |
} | |
$stmt = $db->query('SELECT DISTINCT(Sensor) FROM measure2'); | |
$row_count = $stmt->rowCount(); | |
$sql = 'SELECT Time, '; | |
$dynamic_fields = array(); | |
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { | |
$dynamic_fields[] = $row['Sensor']; | |
$sql .= "MAX(IF(Sensor = '{$row['Sensor']}',Value,0)) AS {$row['Sensor']}"; | |
if ($row_count > 1) { | |
$sql .=','; | |
} | |
$row_count--; | |
} | |
$sql .= ' FROM measure2 GROUP BY Time'; | |
//echo $sql; | |
$pivot = $db->query($sql); | |
while ($row = $pivot->fetch(PDO::FETCH_ASSOC)) { | |
echo $row['Time']; | |
foreach ($dynamic_fields as $field) { | |
echo " , " . $row[$field]; | |
} | |
echo '<br/>'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment