1

By taking mysql database table values, want to create PHP a bar chart. I used JpGraph to draw the bar chart. I want to take data from 'student' table. I has a column named 'category' in which the value is either 'Full time' or 'Part time'. I want to count the no. of rows in which the category is 'Full time' and no.of rows in which the category is 'Part time'. The x-axis should be category and y-axis should be relevant number of rows. The PHP code is as follows;

<?php
 require_once('/jpgraph-3.5.0b1/src/jpgraph.php');
 require_once('/jpgraph-3.5.0b1/src/jpgraph_bar.php'); 
 $db = mysql_connect("localhost", "root","") or die(mysql_error());

 mysql_select_db("mphildatabase",$db) or die(mysql_error());

 $sql1 = mysql_query("SELECT category FROM student") or die(mysql_error());
 $sql2 = mysql_query("SELECT COUNT(*) FROM student WHERE category='Full Time'") or die(mysql_error());
 $sql3 = mysql_query("SELECT COUNT(*) FROM student WHERE category='Part Time'") or die(mysql_error());
 while($row1 = mysql_fetch_array($sql1))
 {
 $row2 = mysql_num_rows($sql2);
 $row3 = mysql_num_rows($sql3);
 $data[] = $row2;
 //$data[] = $row3;
 $leg[] = $row1['category'];
 }
 $graph = new Graph(950,750,"auto");
 $graph->SetScale("textint");
 $graph->img->SetMargin(50,30,50,50);

 $graph->SetShadow();

  $graph->xaxis->SetTickLabels($leg);

  $bplot = new BarPlot($data);
  $bplot->SetFillColor("lightgreen"); 
  $bplot->value->Show();
  $bplot->value->SetFont(FF_ARIAL,FS_BOLD);
  $bplot->value->SetAngle(45);
  $bplot->value->SetColor("black","navy");

  $graph->Add($bplot);
  $graph->Stroke(); ?>

This will give a graph of seperate bars for each row. There will be bars printed for each row and y-axis value of all those bars will be 1. How can I draw a bar graph with only 2 bars, one showing no.of rows in which the category is 'Full Time' and other bar showing no.of rows in which the category is 'Part Time'? Thank you!

1 Answer 1

1

You must use just one query, and fill the arrays in one loop. Your query must be:

"SELECT count(*) as num_rows, category from 
student WHERE category ='Full Time' or Category= 'Part Time'
Group by Category
  "

...

while($row1 = mysql_fetch_array($sql1))
{
$leg[] = $row1['category'];
$data[] = $row1['num_rows']
}
Sign up to request clarification or add additional context in comments.

2 Comments

This will give an error message as 'Either X or Y data arrays contain non numeric values. Check that data is really specified as numeric data and not as strings'. Why is that?
solved! Changed the arrays as $leg[] = $row1['num-rows']; $data[] = $row1['category']; . Thank you @chessar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.