Sunteți pe pagina 1din 19

Mrunal Patekar

mpp333
Database: Problem Set 3
(1)
php Sandwich shop

File:database.php
<?php
$hostname = "localhost";
$database = "sandwich-shop";
$username = "root";
$password = "";
$mysqli = new mysqli($hostname, $username, $password , $database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>

File: index.php

<?php
// Start the session
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Sandwich Shop</title>
<script type="text/javascript">
function validateForm(){
var val = phoneno.value
if (/^\d{10}$/.test(val)) {
// value is ok, use it
} else {
alert("Invalid Phone number; must be ten digits")
phoneno.focus()
return false
}
}
</script>
</head>

<body>
<h2 style="text-align:center;">The Sandwich Shop</h2>
<form id="form1" name="form1" onSubmit="return validateForm()" method="post" action="in.php">
<table width="400" style="margin:0px auto; border:1px solid black;">
<tr>
<td>Enter your Phone Number</td>
<td>
<input type="text" name="phoneno" id="phoneno" />
</tr>
<tr>
<td>Searching For</td>
<td><input type="text" name="searchkey" id="searchkey" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="submit" id="submit" value="Enter" /></td>
</tr>
</table>
</form>
</body>
</html>
File: in.php
<?php
// Start the session
session_start();
$_SESSION['phoneno'] = $_POST['phoneno'];
?>
<?php
include("database.php");
if(isset($_POST["searchkey"]))
{
$orderQuery = "select m.sname, m.size, m.price, s.description
from menu m, sandwich s
where s.description like ?
and m.sname = s.sname GROUP BY m.sname";
$searching = "%{$_POST['searchkey']}%";
$orderStmt = $mysqli->prepare($orderQuery);
$orderStmt->bind_param("s", $searching);
}
else
{
$orderQuery = "select m.sname, m.size, m.price, s.description
from menu m, sandwich s
where m.sname = s.sname";
$orderStmt = $mysqli->prepare($orderQuery);
}
if($orderStmt == false)
{

trigger_error('Wrong SQL: ' . $orderQuery . ' Error: ' . $mysqli->error, E_USER_ERROR);


}
$orderStmt->execute();
$orderStmt->bind_result($s_name, $s_size, $s_price, $s_description);
$result = $orderStmt->get_result();
?>
<html>
<head><title>Sandwich Menu</title>
<SCRIPT TYPE="text/javascript">
function handleClick(myRadio)
{
var str = myRadio.value.split('#');
document.getElementById("o_sname").value = str[1];
document.getElementById("o_size").value = str[2];
document.getElementById("o_phone").value = "<?php echo $_SESSION['phoneno']; ?>";
}
</SCRIPT>
<head>
<body background = blue>
<form name="form1" method="post" action="submission.php">
<input type="hidden" id="o_sname" name="o_sname" value=""/>
<input type="hidden" id="o_size" name="o_size" value=""/>
<input type="hidden" id="o_phone" name="o_phone" value=""/>
<?php
$rowCount = 1;
echo "<div>";
echo "<h2 style=text-align:center;>Select your Sandwich from the Menu</h2>";
echo "<center><table width=800 border='1'>";
echo "<tr><th>Sandwich name</th>";
echo "<th>Sandwich description</th>";
echo "<th>Sandwich Large size and price</th>";
echo "<th>Sandwich Medium size and price</th>";
echo "<th>Sandwich Small size and price</th></tr>";
while ($myrow = $result->fetch_assoc())
{
echo "<tr id='".$myrow['sname']."'>";
echo "<td>".$myrow['sname']."</td>";
echo "<td><p>".$myrow['description']."</p></td>";
$sizeQuery = "select m.size,m.price
from menu m
where m.sname = '".$myrow['sname']."'";
$sizeStmt = $mysqli->prepare($sizeQuery);
$sizeStmt->execute();
$sizeresult = $sizeStmt->get_result();
//print_r($s_size); die;
//echo '<td><select name="s_size">';
while ($myrow1 = $sizeresult->fetch_assoc())
{
echo "<td><label id='lblSize".$rowCount."'>".
$myrow1['size']."</label><label style=margin-left:10%;
id='lblPrice".$rowCount."'>".$myrow1['price']."$</label><input style=float:right; type='radio'

name='rdSandwich' value='rd#".$myrow['sname']."#".$myrow1['size']."'
onclick='handleClick(this);'/></td>";

$rowCount++;
}
echo "</tr>";
}
$sizeStmt->close();
$orderStmt->close();
//echo "<tr><td><input type='submit' name='submit' id='submit' value='Place
Order'></td></tr>";
echo "</table><input type='submit' name='submit' id='submit' value='submit Order'
style=margin:2%;></center>";
echo "<div>";
?>
</form>
</body>
</html>

File: submission.php

<?php
// Start the session
session_start();
?>
<?php
include("database.php");
if(isset($_POST['submit']))
{
if(! get_magic_quotes_gpc() )
{
$o_size = addslashes ($_POST['o_size']);
$o_sname = addslashes ($_POST['o_sname']);
}
else
{
$o_size = $_POST['o_size'];
$o_sname = $_POST['o_sname'];
}
$o_phone = $_SESSION['phoneno'];
echo "<h1 style=text-align:center>Order Summary</h1>";
echo "\n";
echo "<div>";
echo "<center><table border=1 width=500>";
echo "<tr><td>Phone Number:</td><td style=text-align:center> ".$o_phone."</td></tr>";
echo "<tr><td>Sandwich Name:</td><td style=text-align:center> ".$o_sname."</td></tr>";
echo "<tr><td>Size order:</td><td style=text-align:center> ".$o_size."</td></tr>";
echo "</table></center>";
echo "</div>";

$submitQuery = "Select * from orders where phone = ? and sname = ? and size = ? and status
= 'pending'";
$submitStmt = $mysqli->prepare($submitQuery);
if($submitStmt == false)
{
echo "failed";
trigger_error('Wrong SQL: ' . $submitQuery . ' Error: ' . $mysqli->error,
E_USER_ERROR);
}
$submitStmt->bind_param("iss", $o_phone,$o_sname,$o_size);
if(!$submitStmt->execute())
{
echo "Execute failed: (" . $submitStmt->errno . ") " . $submitStmt->error;
}
if (!($submitResult = $submitStmt->get_result()))
{
echo "Getting result set failed: (" . $submitStmt->errno . ") " . $submitStmt->error;
}
if($submitResult->num_rows > 0)
{
$updateInsertQuery = "Update orders set quantity = quantity + 1, o_time = now()
where phone = ? and sname = ? and size = ? and status = 'pending'";
}
else
{
$updateInsertQuery = "Insert into orders values (?, ?, ?, now(), 1, 'pending')";
}
$submitStmt->close();
$updateInsertStmt = $mysqli->prepare($updateInsertQuery);
if($updateInsertStmt == false)
{
echo "failed";
trigger_error('Wrong SQL: ' . $updateInsertQuery . ' Error: ' . $mysqli->error,
E_USER_ERROR);
}
$updateInsertStmt->bind_param("iss", $o_phone,$o_sname,$o_size);
if(!$updateInsertStmt->execute())
{
echo "Execute failed: (" . $updateInsertStmt->errno . ") " . $updateInsertStmt->error;
}
/* if (!($updateInsertResult = $updateInsertStmt->get_result()))
{
echo "Getting result set failed: (" . $updateInsertStmt->errno . ") " .
$updateInsertStmt->error;
} */
echo "<h2 style=text-align:center>Your Order has been placed successfully!!!</h2></br>";
$updateInsertStmt->close();
echo "<center><a href=index.php>Click here to go main page</a></center>";
}
?>
File: sandwich-shop.sql
-- phpMyAdmin SQL Dump
-- version 4.2.7.1

-- http://www.phpmyadmin.net
--- Host: 127.0.0.1
-- Generation Time: Nov 15, 2014 at 02:00 PM
-- Server version: 5.5.39
-- PHP Version: 5.4.31
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;


/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--- Database: `sandwich-shop`
--- ---------------------------------------------------------- Table structure for table `customer`
-CREATE TABLE IF NOT EXISTS `customer` (
`phone` char(10) NOT NULL,
`building_num` int(11) DEFAULT NULL,
`street` varchar(20) DEFAULT NULL,
`apartment` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--- Dumping data for table `customer`
-INSERT INTO `customer` (`phone`, `building_num`, `street`, `apartment`) VALUES
('1234567891', 10, 'Avenue street', '10'),
('2223334445', 20, 'bay street', '13'),
('3334445556', 30, 'jump street', '14'),
('6667778889', 40, 'journal street', '2');
-- ---------------------------------------------------------- Table structure for table `menu`
-CREATE TABLE IF NOT EXISTS `menu` (
`sname` varchar(20) NOT NULL DEFAULT '',
`size` varchar(20) NOT NULL DEFAULT '',
`price` decimal(4,2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--- Dumping data for table `menu`


-INSERT INTO `menu` (`sname`, `size`, `price`) VALUES
('Cheese Burger', 'large', '18.00'),
('Cheese Burger', 'medium', '10.00'),
('Cheese Burger', 'small', '7.00'),
('Grilled Chicken', 'large', '20.00'),
('Grilled Chicken', 'medium', '15.00'),
('Grilled Chicken', 'small', '12.00'),
('Egg Salad Sandwich ', 'large', '10.00'),
('Egg Salad Sandwich ', 'medium', '8.00'),
('Egg Salad Sandwich ', 'small', '6.00');
-- ---------------------------------------------------------- Table structure for table `orders`
-CREATE TABLE IF NOT EXISTS `orders` (
`phone` char(10) NOT NULL DEFAULT '',
`sname` varchar(20) NOT NULL DEFAULT '',
`size` varchar(20) NOT NULL DEFAULT '',
`o_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`quantity` int(11) DEFAULT NULL,
`status` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--- Dumping data for table `orders`
-INSERT INTO `orders` (`phone`, `sname`, `size`, `o_time`, `quantity`, `status`) VALUES
('1234567891', 'Cheese Burger', 'medium', '2014-11-13 16:10:31', 1, 'pending'),
('1234567891', 'Egg Salad Sandwich ', 'medium', '2014-11-13 17:03:19', 2, 'pending'),
('1234567891', 'Egg Salad Sandwich', 'small ', '2014-11-13 16:19:02', 3, 'served'),
('1234567891', 'Egg Salad Sandwich ', 'small', '2014-11-13 17:06:43', 1, 'pending'),
('2223334445', 'Cheese Burger', 'medium', '2014-11-09 07:16:00', 1, 'served'),
('2223334445', 'Cheese Burger', 'medium', '2014-11-13 16:15:08', 1, 'pending'),
('2223334445', 'Egg Salad Sandwich', 'medium', '2014-11-14 11:45:02', 1, 'pending'),
('3334445556', 'Grilled Chicken', 'large', '2014-11-08 11:25:00', 2, 'served'),
('6667778889', 'Cheese Burger', 'small', '2014-11-09 15:34:00', 1, 'served');
-- ---------------------------------------------------------- Table structure for table `sandwich`
-CREATE TABLE IF NOT EXISTS `sandwich` (
`sname` varchar(20) NOT NULL,
`description` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--- Dumping data for table `sandwich`


-INSERT INTO `sandwich` (`sname`, `description`) VALUES
('Cheese Burger', 'simple cheese sandwich'),
('Grilled Chicken', 'non veg sandwich'),
('Egg Salad Sandwich ', 'So tasty ');
--- Indexes for dumped tables
---- Indexes for table `customer`
-ALTER TABLE `customer`
ADD PRIMARY KEY (`phone`);
--- Indexes for table `menu`
-ALTER TABLE `menu`
ADD PRIMARY KEY (`sname`,`size`);
--- Indexes for table `orders`
-ALTER TABLE `orders`
ADD PRIMARY KEY (`phone`,`sname`,`size`,`o_time`), ADD KEY `sname` (`sname`,`size`);
--- Indexes for table `sandwich`
-ALTER TABLE `sandwich`
ADD PRIMARY KEY (`sname`);
--- Constraints for dumped tables
---- Constraints for table `menu`
-ALTER TABLE `menu`
ADD CONSTRAINT `menu_ibfk_1` FOREIGN KEY (`sname`) REFERENCES `sandwich` (`sname`);
--- Constraints for table `orders`
-ALTER TABLE `orders`
ADD CONSTRAINT `orders_ibfk_1` FOREIGN KEY (`phone`) REFERENCES `customer` (`phone`),
ADD CONSTRAINT `orders_ibfk_2` FOREIGN KEY (`sname`, `size`) REFERENCES `menu` (`sname`,
`size`);

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;


/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

(2) Consider a relational schema R = (A, B, C, D, E, F) satisfying the following functional dependencies:
F = { C B, CB AC, CAE FB, D E, CA B }
a) Derive all candidate keys for this schema.
CB
CBAC
BA
CA
CAEFB
EF
DE
DF
CADEAD
CADFAD
CADFBD
CADFCD
CDB
CDA
CDED
CDFD
CDCD
CDABCDEF
So CD is the candidate key.
(b) Derive a canonical cover of the functional dependencies in F.
F = { C B, CB AC, CAE FB, D E, CA B }

(1.)Singleton RHS
C B, CB A, CBC ,CAE F, CAE B ,D E, CA B }
(2.)No extraneous LHS attributes.
CB A
C closure is CBA
So we can remove B

So, C A

CBC
C closure is CBA
So, we get CC..(we will not be including this in canonical cover)
CAE F
C closure is CBA
So we can remove A
So, we get CE F
So the canonical cover is: CA, CB, CEF, DE

(c) Is the above schema in BCNF? Prove or disprove. If it is not in BCNF, convert it into BCNF.
No the above schema is not in BCNF.
Our candidate key is CD.
And it is not included on the left hand side of the functional dependency.

On converting the above schema in BCNF, we get:


ABCDEF
(CA) (CBDEF)
(CA) (CB) (CDEF)
(CA) (CB) (CEF) (CED)
(CA) (CB) (CEF) (DE) (CD)
Now it is in BCNF
(d) d) Is the BCNF schema from c) dependency-preserving? Prove or disprove. If not, convert it into 3NF.
Yes the above schema is dependency preserving.
As all the above functional dependency got satisfied.

Quest 3
VideoStore (cid, cname, ccity, bid, bname, bcity, mid, mtitle, mgenre, myear, copyid, rentdate,
returndate, cost)
(a)It is not a good relational schema.

Because there are too many attributes in one single table, this will cause lot of redundancies.
If we say that 2 customers want to buy the same movie from the same branch then it will cause lot of
redundancy which is not correct.
Here cname, ccity are dependent on cid and so they can be written in a separate relation . Same can
be said for bname, bcity as they are associated with bid.
This schema will result in update, insert and deletion anomalies.
Example : 1 customer cannot buy from more than one branches . Moreover the customer cannot buy
the movie again ( assuming cid as the key)

New data cannot be added .


Even if new data is added null values are introduced which is not desirable.

(b) The candidate keys are as follows:


(cid , bid, copyid, mid, rentdate, returndate)
(cid, bid , copyid , mtitle, myear, rentdate , returndate)
(c) The non trivial functional dependencies are:
cid cname, ccity
bid bname, bcity
cid, copyid, bid, mid, rentdate, returndate cost
mid mtitle, mgenre, myear
mtitle, myear mid
(d) Derive a canonical cover of the functional dependencies in F.
cid cname, ccity
bid bname, bcity
cid, copyid, bid, mid, rentdate, returndate cost
mid mtitle, mgenre, myear
mtitle, myear mid
(e) Is the above schema in BCNF? Prove or disprove. If it is not in BCNF, convert it into BCNF.
No the schema is not in BCNF as, if we consider the functional dependency, cid cname, ccity ; cid is
neither a candidate key nor a trivial dependency.
So the BCNF is
(cid , cname, ccity)
(bid , bname, bcity)
(cid, copyid, bid, mid, rentdate, returndate, cost)
(mid, mtitle, mgenre, myear)
(mid, cid, copyid, bid, returndate, rentdate)
(f) Is the BCNF schema from d) dependency-preserving? Prove or disprove. If not, convert it into
3NF.
The schema is in BCNF as all functionality is dependency preserving.
As the canonical cover,
cid cname, ccity [Corresponding BCNF is (cid , cname, ccity)]
bid bname, bcity [Corresponding BCNF is (bid , bname, bcity)]
cid, copyid, bid, mid, rentdate, returndate cost [Corresponding BCNF is (cid, copyid, bid, mid,
rentdate, returndate, cost)]
mid mtitle, mgenre, myear [Corresponding BCNF is (mid, mtitle, mgenre, myear)
mtitle, myear mid [Corresponding BCNF is (mid, mtitle, mgenre, myear)]
(g) Now suppose that a customer can only rent movies from branches that are located in the same city
where
they live. How would this change your answer to parts b) to f)?

g(b) Derive all candidate keys for this schema.


The candidate key (cid, copyid, mid, returndate, rentdate)

g(c) Identify the set F of non-trivial functional dependencies for this schema. (It is enough to
identify a subset E such that the closures of E and F are the same.)
Functional Dependencies are:
cid bid
cid cname, ccity
bid bname, bcity
cid, copyid, bid, mid, rentdate, returndate cost
mid mtitle, mgenre, myear
mtitle, myear mid

g(d) Derive a canonical cover of the functional dependencies in F using the steps mentioned in
one of the question above .
We get the following functional dependencies which are in the canonical form
cid bid
cid cname, ccity
bid bname, bcity
cid, copyid, bid, mid, rentdate, returndate cost
mid mtitle, mgenre, myear
mtitle, myear mid
g(e) Is the above schema in BCNF? Prove or disprove. If it is not in BCNF, convert it into BCNF.
No the schema is not in BCNF
So the relations that are in BCNF are as follows:
(cid , cname, ccity)
(bid , bname, bcity)
(cid, copyid, bid, mid, rentdate, returndate, cost)
(mid, mtitle, mgenre, myear)
(mid, cid, copyid, rentdate, returndate)
(cid,bid)
Here the BCNF is lossy BCNF as mtitle, myear mid is not satisfied.
g(f) Is the BCNF schema from d) dependency-preserving? Prove or disprove. If not, convert it into
3NF.
The above BCNF is dependency preserving .
(h)Now remove the assumption in g) again. Suppose we change the copyID in the schema so that it is
globally unique, meaning that no two copies can have the same copyID, even if they are copies of
different movies at different branches. How does this change your answers to parts b) to f)?
h(b) Derive all candidate keys for this schema.
Candidate keys:
(cid , bid, copyid, mid, rentdate, returndate)
(cid, bid , copyid , mtitle, myear , rentdate, returndate)

h(c) Identify the set F of non-trivial functional dependencies for this schema. (It is enough to
identify a subset E such that the closures of E and F are the same.)
Functional Dependencies are:
cid cname, ccity
bid bname, bcity
cid, copyid, rentdate, returndate cost
mid mtitle, mgenre, myear
mtitle, myear mid

h(d) Derive a canonical cover of the functional dependencies in F.


cid cname, ccity
bid bname, bcity
cid, copyid, rentdate, returndate cost
mid mtitle, mgenre, myear
mtitle, myear mid

h(e) Is the above schema in BCNF? Prove or disprove. If it is not in BCNF, convert it into
BCNF.
No the schema is not in BCNF as, if we consider the functional dependency, cid cname, ccity ; cid
is neither a candidate key nor a trivial dependency.
So the BCNF is
(cid , cname, ccity)
(bid , bname, bcity)
(cid, copyid, mid, rentdate, returndate, cost)
(mid, mtitle, mgenre, myear)
(mid, cid, bid ,copyid, returndate, rentdate )
h(f) Is the BCNF schema from d) dependency-preserving? Prove or disprove. If not, convert it
into 3NF.
The above BCNF is dependency preserving as the functional dependency gets preserved.

Quest 4
The following database is used:
CUSTOMER TABLE

MOVIE TABLE

BRANCH TABLE

COPY TABLE

RENTAL TABLE

(a)
create view AvailableMovies as

( SELECT movie.title, branch.bid


FROM Movie , branch ,copy
where movie.mid = copy.mid and branch.bid = copy.bid
and
movie.mid in
( SELECT movie.mid
FROM Copy
WHERE copyid NOT IN
( SELECT copyid
FROM rented
WHERE returndate is null))
group by movie.title,branch.bid )
Output:
select * from AvailableMovies

(b)
create view CustView as
( select cid , cname
from customer )
Output:

Yes it is possible to insert a new tuple into the view custview.


A view acts as a virtual table. In an updatable view it is possible to insert a new topple, as you can see it
below.
When the view gets updated with a new tuple the original table too gets updated.
In the following view we are adding the tuple (111111 , Tom Cruize)
Here the original table get values as null for the coloms which were not included in the insert statement.

insert into CustView values (11111,'Tom Cruize')

Output:

Original table which got updated because we inserted the tuple (111111 , Tom Cruize) in the view
custview:

(c) CREATE trigger display_address_change


AFTER UPDATE ON customer
FOR EACH ROW
Insert into customer_old_address values (OLD.cid,OLD.caddress);
update customer
set caddress = "Brooklyn"
where cid = '15674';
select * from customer_old_address;

After creating trigger and Before Insert.

After updation values get inserted automatically into customer_old_address.

(d) Add a new table OldAddresses that stores the old address of a customer when the customer does an
address
change. Then implement a trigger that adds the cid and old address to this table whenever the address
attribute in the Customer table is updated. (Check: does the table contain an address?)
insert into copy
(copyid,mid,bid)
(select R1.copyid+1, R1.mid, R1.bid from
(select cp.copyid, b.bid, m.mid, count(m.title) as Movie_count
from branch b, movie m, copy cp, rented r
where cp.bid = b.bid and cp.mid = m.mid and
r.copyid = cp.copyid
group by b.bname, m.title)R1,
(select b.bid, m.mid, count(m.title) as Total
from branch b, movie m, copy cp, rented r
where cp.bid = b.bid and cp.mid = m.mid and
r.copyid = cp.copyid
group by b.bname)R2
where R1.bid = R2.bid
and R1.Movie_count/R2.Total > 0.9);

Before Query:

After the query:

(e) Query to get total number of attributes in the database:


SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = 'assignment3'

Query to get total number of tables in the database:


SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'assignment3'

(f) Write a query that lists all foreign keys in this database
SELECT
concat(table_name, '.', column_name) as 'foreign key',
concat(referenced_table_name, '.', referenced_column_name) as 'references'
FROM
information_schema.key_column_usage

WHERE
referenced_table_name is not null AND
table_schema = 'assignment3'

(g) Select TABLE_NAME from INFORMATION_SCHEMA.COLUMNS


Where column_name like '%name%' and
table_schema = 'assignment3'

S-ar putea să vă placă și