我在libchart
中使用PHP
,但我对如何统计数据库中的男性和女性有疑问。我正在使用wampserver
:
<?php
include "../libchart/libchart/classes/libchart.php";
define('DB_HOST', 'localhost');
define('DB_NAME', 'login');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
header("Content-type: image/png");
$chart = new PieChart(500, 300);
$query1= "Select count(*) from users where gender='Male'";
$query2= "Select count(*) from users where gender='Female'";
$male=$query1;
$female=$query2;
$dataSet = new XYDataSet();
$dataSet->addPoint(new Point("Male", $male));
$dataSet->addPoint(new Point("Female", $female));
$chart->setDataSet($dataSet);
$chart->setTitle("Number of Female and Male");
$chart->render();
?>
答案 0 :(得分:0)
您永远不会费心执行查询 - 您所做的就是定义一些在其中包含SQL的字符串。另外,不需要两个单独的查询:
$sql = "SELECT gender, count(*) AS cnt FROM users WHERE gender IN ('Male', 'Female') GROUP BY gender");
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$dataSet->addPoint(new Point($row['gender'], $row['cnt']));
}
答案 1 :(得分:0)
<?php
include "../libchart/libchart/classes/libchart.php";
define('DB_HOST', 'localhost');
define('DB_NAME', 'login');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
header("Content-type: image/png");
$chart = new PieChart(500, 300);
$query = "Select (Select count(*) from users where gender='Male') AS Male, (Select count(*) from users where gender='Female') as Female";
$data = mysql_query($query);
$male=$data[0]['Male'];
$female=$data[0]['Male'];
$dataSet = new XYDataSet();
$dataSet->addPoint(new Point("Male", $male));
$dataSet->addPoint(new Point("Female", $female));
$chart->setDataSet($dataSet);
$chart->setTitle("Number of Female and Male");
$chart->render();
?>