Skip to content

Instantly share code, notes, and snippets.

@hanafiah
Last active August 29, 2015 13:56
Show Gist options
  • Save hanafiah/8916872 to your computer and use it in GitHub Desktop.
Save hanafiah/8916872 to your computer and use it in GitHub Desktop.
generate pivot table
<?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