Page 1 of 1

Displaying two variables nested under each other

Posted: Fri Apr 10, 2009 9:24 pm
by Dilnesaw
Greetings,

It is my first time to post here. I have a PHP syntax that prints data from mysql database. In this case, it summarizes Gender (F, M, total) as count and percentage distribution. Now I want to crosstab Gender with ethnicity. I want to group gender under "Ethnicity". To display Gender nested under Ethnicity (keeping Ethnicity as column and Gender as row), how can I do that? I couldn't find any crosstabs in PHP. I tried group by also. My ethncity break down will be "Asian", "Black", and "White".

I would really appreciate any help? Thanks.

<?php
$link = mysql_connect("***", "****", "****");
mysql_select_db("****") or die(mysql_error());
$sql = "SELECT Gender, COUNT(*) AS total FROM New GROUP BY Gender WITH ROLLUP";
$result = mysql_query($sql);
$data = array();
while($row = mysql_fetch_assoc($result))
{
$key = !empty($row['Gender']) ? $row['Gender'] : 'Total';
$data[$key] = $row['total'];
}
$grandTotal = $data['Total'];
echo "<table width='50%' border='4' cellspacing='0' cellpadding='10' align='center'>";
echo "<tr><th>Gender</th><th>Number</th><th>Percent</th></tr>";
foreach($data as $gender => $total)
{
printf(
"<tr align='center'><td>%s</td><td>%d</td><td>%d%%</td></tr>",
$gender,
$total,
round($total/$grandTotal*100, 0)
);
}
echo "</table>";
?>

Re: Displaying two variables nested under each other

Posted: Mon Apr 13, 2009 8:19 pm
by Dilnesaw
McInfo,

Million thanks. I was really impressed by the step-by-step instruction you provided. I appreciate. I am going to try with mysql database.