13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

638 Chapter 28 Building a Shopping Cart<br />

Listing 28.15<br />

Continued<br />

}<br />

return false;<br />

// insert each book<br />

foreach($_SESSION['cart'] as $isbn => $quantity) {<br />

$detail = get_book_details($isbn);<br />

$query = "delete from order_items where<br />

orderid = '".$orderid."' <strong>and</strong> isbn = '".$isbn."'";<br />

$result = $conn->query($query);<br />

$query = "insert into order_items values<br />

('".$orderid."', '".$isbn."', ".$detail['price'].", $quantity)";<br />

$result = $conn->query($query);<br />

if(!$result) {<br />

return false;<br />

}<br />

}<br />

// end transaction<br />

$conn->commit();<br />

$conn->autocommit(TRUE);<br />

}<br />

return $orderid;<br />

?><br />

The insert_order() function is rather long because you need to insert the customer’s<br />

details, order details, <strong>and</strong> details of each book she wants to buy.<br />

You will note that the different parts of the insert are enclosed in a transaction, beginning<br />

with<br />

$conn->autocommit(FALSE);<br />

<strong>and</strong> ending with<br />

$conn->commit();<br />

$conn->autocommit(TRUE);<br />

This is the only place in this application where you need to use a transaction. How do<br />

you avoid having to do it elsewhere? Look at the code in the db_connect() function:<br />

function db_connect() {<br />

$result = new mysqli('localhost', 'book_sc', 'password', 'book_sc');<br />

if (!$result) {<br />

return false;<br />

}<br />

$result->autocommit(TRUE);<br />

return $result;<br />

}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!