Thursday, September 13, 2012

SQL BETWEEN Operator


MySQL BETWEEN Operator 
BETWEEN operator is used to select a range of data between two values.Here in this example we select the data between two dates.
Create table product_issue in your my_database.

CREATE TABLE IF NOT EXISTS `product_issue` (
  `id` int(30) NOT NULL AUTO_INCREMENT,
  `date` date NOT NULL,
  `name` varchar(40) NOT NULL,
  `quantity` varchar(40) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

--
-- Dumping data for table `product_issue`
--

INSERT INTO `product_issue` (`id`, `date`, `name`, `quantity`) VALUES
(1, '2012-09-01', 'Computers', '12'),
(2, '2012-09-02', 'Mouses', '20'),
(3, '2012-09-03', 'Key Boards', '23'),
(4, '2012-09-05', 'UPS', '12'),
(5, '2012-09-06', 'Monitors', '40'),
(6, '2012-09-07', 'CPU', '22');

Next create bellow PHP file and find the result between 2012-09-01-2012-09-05,For the posting of these two dates to php file create bellow HTML file also.

HTML file 




<table bgcolor=#cccccc align="center">
<form action="find.php" method="post">
<tr><td><input type="text" name="date1"></td></tr>
<tr><td><input type="text" name="date2"></td></tr>
<tr><td><input type="submit" name="Find"></td></tr>
</form>
</table>

find.php

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

mysql_select_db("my_database", $con);

$result = mysql_query("SELECT*FROM product_issue WHERE date BETWEEN '$date1' AND '$date2'");

echo "<table border='1' align='center'>
<tr>
<th>Date</th>
<th>Item</th>
<th>Amount</th>
</tr>";
while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['date'] . "</td>";
  echo "<td>" . $row['name'] . "</td>";
  echo "<td>" . $row['quantity'] . "</td>";
 echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

Date Item Amount
2012-09-01Computers12
2012-09-02Mouses20
2012-09-03Key Boards23
2012-09-05UPS12

No comments:

Post a Comment