是否可以从下面类似的3段创建1段代码?
每个段落之间的区别是:
* SQL查询WHERE模型= $
* $系列? = new XYDataSet()
* addSerie(“Model”,$ serie ??)
* $ serie ?? - > addPoint
$chart = new LineChart(1800, 500);
$dataSet = new XYSeriesDataSet();
$sql = mysql_query("SELECT Date, SUM(Qty_sum) AS Qty_sum FROM stats WHERE Model = 'ESD' GROUP BY MONTH(Date)");
$serie1 = new XYDataSet();
$dataSet->addSerie("ESD", $serie1);
while($row = mysql_fetch_assoc($sql)) {
$date = date('M', strtotime($row['Date']));
$qty = $row['Qty_sum'];
$serie1->addPoint(new Point("$date", $qty));
}
$sql2 = mysql_query("SELECT Date, SUM(Qty_sum) AS Qty_sum FROM stats WHERE Model = 'POSA' GROUP BY MONTH(Date)");
$serie2 = new XYDataSet();
$dataSet->addSerie("POSA", $serie2);
while($row = mysql_fetch_assoc($sql2)) {
$date = date('M', strtotime($row['Date']));
$qty = $row['Qty_sum'];
$serie2->addPoint(new Point("$date", $qty));
}
$sql3 = mysql_query("SELECT Date, SUM(Qty_sum) AS Qty_sum FROM stats WHERE Model = 'POSA MM/SAT' GROUP BY MONTH(Date)");
$serie3 = new XYDataSet();
$dataSet->addSerie("POSA MM/SAT", $serie3);
while($row = mysql_fetch_assoc($sql3)) {
$date = date('M', strtotime($row['Date']));
$qty = $row['Qty_sum'];
$serie3->addPoint(new Point("$date", $qty));
}
$chart->setDataSet($dataSet);
答案 0 :(得分:0)
如果您创建一个数组,
$things = ['ESD', 'POSA', 'POSA MM/SAT'];
您可以循环访问代码3次,并在必要时替换值。
即
foreach($things as $thing){
$sql = mysql_query("SELECT Date, SUM(Qty_sum) AS Qty_sum FROM stats WHERE Model = '" . $thing . "' GROUP BY MONTH(Date)");
$series[$thing] = new XYDataSet();
$dataSet->addSerie($thing, $series[$thing]);
while($row = mysql_fetch_assoc($sql)) {
$date = date('M', strtotime($row['Date']));
$qty = $row['Qty_sum'];
$series[$thing]->addPoint(new Point("$date", $qty));
}
}
答案 1 :(得分:0)
以下是我在一次SQL查询过程中编写代码的方法。
$chart = new LineChart(1800, 500);
$dataSet = new XYSeriesDataSet();
使模型成为一个数组,在一个地方声明。
$models = ['ESD', 'POSA', 'POSA MM/SAT'];
为每个模型创建一个系列数组并初始化数据集对象。
$series = [];
foreach ($models as $model) {
$series[$model] = new XYDataSet();
}
使用PDO,以便在SQL中使用参数化的IN()
谓词。每个模型需要一个占位符,因此根据$ models数组的大小生成占位符列表。
我也在SQL中进行日期格式化(参见http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format)
$placeholders = implode(",", array_fill(1, count($models), "?"));
$stmt = $pdo->prepare("
SELECT Model, DATE_FORMAT(Date, '%b') AS Mon, SUM(Qty_sum) AS Qty_sum
FROM stats
WHERE Model IN ($placeholders)
GROUP BY Model, Mon");
很容易将模型数组传递给准备好的查询,以匹配SQL查询中的占位符。
$stmt->execute($models);
结果集将按模型和按月分组。
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$point = new Point($row['Mon'], $row['Qty_sum']));
$series[$row['Model']]->addPoint($point);
}