Monday, 5 May 2014

Sum Function Using PHP and MySQL



Database

CREATE TABLE IF NOT EXISTS `products` (
  `id` varchar(30) NOT NULL DEFAULT '',
  `name` varchar(60) NOT NULL DEFAULT '',
  `type` varchar(30) NOT NULL DEFAULT '',
  `price` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `products`
--

INSERT INTO `products` (`id`, `name`, `type`, `price`) VALUES
('1234511', 'Kenny G Hits', 'Music', '25.36'),
('123452', 'Play Station 1', 'Toy', '234.34'),
('676767', 'Rambo Guns', 'Toy', '90.12'),
('1234545', 'Adidas T-Shirt', 'Clothing', '45.20'),
('123455', 'Blouse', 'Clothing', '34.97'),
('123456', 'Bon Jovi Concert Tour', 'Music', '6.95'),
('7878787', 'Vice Ganda', 'Music', '1.25'),
('123458', 'Ham Burger', 'Food', '12.38'),
('4545434', 'RoboCop 2 Action Figure', 'Toy', '56.12'),
('454545', 'Me Jeans', 'Clothing', '8.65'),
('56565656', 'Chocolate Cake', 'Food', '45.12'),
('5656565', 'Pansit Canton', 'Food', '12.54');



PHP File.. index.php



<html>
<head>
<STYLE TYPE="text/css">
TD
{
font-family: Arial;
font-size: 13pt;
font-weight: bold;
color: green;
}


th
{
font-family: Arial;
font-size: 15pt;
color: blue;
}


h2
{
font-family: Arial;
font-size: 16pt;
color: blue;
}
</STYLE>
</head>
<body>
<hr style = 'background-color:green; border-width:2; color:green; height:8px; lineheight:0; display: inline-block; text-align: center; width:100%;' />
<h2 align="center"> Sum Function in PHP and MySQL </h2>
<hr style = 'background-color:green; border-width:2; color:green; height:8px; lineheight:0; display: inline-block; text-align: center; width:1000%;' />
<br><br>

<?php

$conn = mysql_connect("localhost","root","")
or die("cannot connected");
mysql_select_db("product",$conn);


$query = "SELECT name,type,price  FROM products  ";
   
$result = mysql_query($query) or die(mysql_error());
echo "<table border='1' align='center' >";
echo "<tr><th>PRODUCT</th>
<th>TYPE</th>
<th>COST</th>";
echo "</tr>";
   
// Print out result


while($row = mysql_fetch_array($result))
{
    echo "<tr>";
    echo "<td>" .$row['name']."</td>";
    echo "<td> " .$row['type']."</td>";
    echo "<td> " .$row['price']."</td>";
    echo "</tr>";
   
 }  

echo "</table> ";

 echo "<br><br>";


$query = "SELECT type, SUM(price) FROM products group by type ";
   
$result = mysql_query($query) or die(mysql_error());


// Print out result
while($row = mysql_fetch_array($result))

{
    echo "<center>";
    echo "<font size='5' color='red' face='arial'>";
    echo "Total ". $row['type']. " = $ ". $row['SUM(price)'];
    echo "<br /> </font> </center>";
}
?>
</body>
</html>

No comments:

Post a Comment