Sunday, July 8, 2012

MySQL IN Clause

MySQL IN Clause


When you need to have quarterly production in a year you have to break down the months into block like (January, February, March),(April,May,June) etc.Also you need to retrieve these block of data from the database. For this tutorial,I have created following table called "progress" in my-database.

CREATE TABLE IF NOT EXISTS `progress` (
  `id` int(30) NOT NULL AUTO_INCREMENT,
  `Month` varchar(60) NOT NULL,
  `Production` varchar(60) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;

--
-- Dumping data for table `progress`
--

INSERT INTO `progress` (`id`, `Month`, `Production`) VALUES
(1, 'January', '10'),
(2, 'February', '20'),
(3, 'March', '12'),
(4, 'April', '21'),
(5, 'May', '23'),
(6, 'June', '21'),
(7, 'July', '23'),
(8, 'August', '27'),
(9, 'September', '32'),
(10, 'October', '14'),
(11, 'November', '25'),
(12, 'December', '24');

Create the following php file to display the data for first quarter(January, February, march)


<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_database", $con);

$result = mysql_query("SELECT * FROM progress WHERE Month IN ( 'January', 'February', 'March' )");

echo "<table border='1'>
<tr>
<th>Month</th>
<th>Nuber of Products</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['Month'] . "</td>";
  echo "<td>" . $row['Production'] . "</td>";
echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>
Month Nuber of Products
January10
February20
March12

No comments:

Post a Comment