Reputation: 23
I have this loop that outputs to a graph. Over time, the data in my 'history' table grows dramatically and I want to cut down on the amount being outputted onto the graph, by selecting every other result.
How can I do this with my code?
<?php
$cdate = 0;
$counter = 0;
$sql = "SELECT * FROM history WHERE time < '$ctime' ORDER BY time asc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$cdate = ($row["time"]);
$sql1 = "SELECT AVG(value) AS avgval FROM history WHERE time = '$cdate' AND time < '$ctime'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while($row1 = $result1->fetch_assoc()) {
$avgval = $row1["avgval"];
echo "[new Date((".($row["time"] * 1000).")), ".$avgval."],";
}
}
}
}
?>
For example, if I have this in my table (history):
[id] --- [ticker] --- [value] --- [time]
1 --- Group1 --- 100 --- 730
2 --- Group 2 --- 200 --- 730
3 --- Group 1 --- 110 --- 740
4 --- Group 2 --- 235 --- 740
5 --- Group 1 --- 310 --- 750
6 --- Group 2 --- 485 --- 750
How can I just output the average of #1, #2 and the average of #5, #6 - ignoring #4 and #5?
Upvotes: 2
Views: 58
Reputation: 1570
<?php
$cdate = 0;
$counter = 0;
$sql = "SELECT * FROM history WHERE time < '$ctime' ORDER BY time asc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$cdate = ($row["time"]);
$sql1 = "SELECT AVG(value) AS avgval FROM history WHERE time = '$cdate' AND time < '$ctime'";
$result1 = $conn->query($sql1);
$i = 0; // incrementor
if ($result1->num_rows > 0) {
while($row1 = $result1->fetch_assoc()) {
++$i; // plus one
if($i % 2 == 0) { // check if $i is even
$avgval = $row1["avgval"];
echo "[new Date((".($row["time"] * 1000).")), ".$avgval."],";
}
}
}
}
}
?>
Upvotes: 1