Bai 7 PHP ket noi CSDL MySQL
Trang 1KHOA CÔNG NGHỆ THÔNG TIN – ĐẠI HỌC KHOA HỌC TỰ NHIÊN
2007 Authored by: Ngô Bá Nam Phương - Lương Vĩ Minh Bài 7 : PHP kết nối CSDL MySQL
Môn : Lập trình và Thiết kế Web 1
Trang 2Bài 7 : PHP kết nối CSDL MySQL
Môn : Lập trình và Thiết kế Web 1
Yêu cầu: Trong ứng dụng BookStore Online, xây dựng các chức năng Tìm kiếm, Thêm,
Xóa, Cập nhật thông tin sách
1 C ấu trúc thư mục :
Tạo thư mục có cấu trúc như sau trong thư mục C:\wamp\www\ để lưu website
BookStoreOnline:
C:\wamp\www\BookStoreOnline\
C:\wamp\www\BookStoreOnline\script\ : Chứa các file javascript
C:\wamp\www\BookStoreOnline\css\ : Chứa các file định dạng css
C:\wamp\www\BookStoreOnline\BookImages\ : Chứa ảnh bìa của các cuốn sách
C:\wamp\www\BookStoreOnline\ : Chứa các trang php, html
2 C ấu trúc CSDL :
Sử dụng MySQL, tạo CSDL gồm 3 bảng Book, Category, Publisher có cấu trúc như sau: a- Bảng Book :
b- Bảng Category :
Trang 4Tạo file DataProvider.php
Lưu DataProvider.php trong thư mục C:\wamp\www\BookStoreOnline\
Khai báo class DataProvider trong DataProvider.php
$connection = mysql_connect("localhost","root","") or
die ("couldn't connect to localhost");
// ebookDB : Tên CSDL
mysql_select_db("ebookDB",$connection);
mysql_query("set names 'utf8'");
$result = mysql_query($sql,$connection);
mysql_close($connection);
return $result; }
Trang 5Để thực thi hàm static trong vsphp:
Trong VS.PHP, từ cửa sổ Solution Explorer, chọn PHP Project R-Click Properties
Chọn Configuration Manager
Trong mục Active solution platform, chọn PHP 5:
Trang 7<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dang nhap he thong</title>
</head>
<body>
<form name="formDangnhap" method="post" action ="DangNhap.php">
<table width="400" border="0">
Trang 8<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dang nhap he thong</title>
</head>
<body>
<?php
$tenDangNhap = $_REQUEST["txtTenDangNhap"];
$matKhau = $_REQUEST["txtMatKhau"];
if($tenDangNhap == $row["UserName"] &&
$matKhau == $row["Password"]) {
$ketQuaDangNhap = true; }
} }
if($ketQuaDangNhap == false)
Trang 9<form name="formDangnhap" method="post" action="DangNhap.php">
<table width="400" border="0">
?>
</body>
</html>
Trang 10<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tim sach</title>
</head>
<body>
<form name="form1" method="post" action ="xlTimSach.php">
<table width="400" border="0">
Trang 132 Xử lý tìm sách
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Xu ly tim kiem</title>
// lấy tên sách tu trang TimKiem.php
$tenSach = $_REQUEST["txtTenSach"];
Trang 14$maSach = $row["BookID"];
$tenSach = $row["BookTitle"];
$giaTien = $row["BookPrice"];
<form name="form1" method="post" action="xlXoa.php">
<input type="hidden" name="BookIDDeleted" value="<?php echo($maSach); ?>" >
Trang 15echo ("Không tìm thấy sách với tựa " $tenSach);
Trang 163 Xử lý Phân trang xlTimsach.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" transitional.dtd">
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
// if $_GET['page'] defined, use it as page number
if(isset($_GET['page']))
{
$pageNum = $_GET['page'];
}
$offset = ($pageNum - ) * $rowsPerPage;
// lấy tên sách tu trang TimKiem.php
$tenSach = $_REQUEST["txtTenSach"];
include_once("DataProvider.php");
Trang 17$sql = "Select * From Book Where BookTitle like '%" $tenSach "%'";
$sql = " LIMIT $offset, $rowsPerPage";
$dsSach = DataProvider::ExecuteQuery($sql);
if($dsSach != false)
{
if(mysql_num_rows($dsSach)>0) {
$maSach = $row["BookID"];
$tenSach = $row["BookTitle"];
$giaTien = $row["BookPrice"];
Trang 18<form name="form1" method="post" action="xlXoa.php">
<input type="hidden" name="BookIDDeleted" value="<?php echo($maSach); ?>" >
<input type="submit" name="btnXoa" value="Xóa" >
// xuất ra danh sách các link liên kết phân trang
$sql = "SELECT COUNT(BookID) AS numrows FROM Book where BookTitle like '%"
$_REQUEST["txtTenSach"] "%'";
$result = DataProvider::ExecuteQuery($sql) ;
Trang 19$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
$maxPage = ceil($numrows / $rowsPerPage);
// print the link to access each page
$self = $_SERVER['PHP_SELF'];
$nav = '';
for($page = ; $page <= $maxPage; $page ++)
{
if ($page == $pageNum) {
$nav = " $page "; // no need to create a link to current page
} else {
$nav = " <a href='" $self "?page=" $page;
$nav = "&txtTenSach=" $_REQUEST["txtTenSach"]."' >" $page "</a> "; }
echo $nav; }
else {
echo ("Không tìm thấy sách với tựa " $tenSach);
}
?>
Trang 214.4 Trang xử l y xóa sách ( xlXoa.php )
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Xu ly Xoa sach</title>
Trang 22<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Them mot cuon sach</title>
<legend>Thông tin sách</legend>
<table width="600" border="0">
Trang 23$maTheLoai = intval ($row["CategoryID"]);
$tenTheLoai = $row["CategoryName"];
<td>Danh sách tên tác giả</td>
<td><input type="text" name="txtTacGia" /></td>
Trang 24$maNhaXuatBan = $row["PublisherID"];
$tenNhaXuatBan = $row["PublisherName"];
Trang 25Bổ xung mã lệnh xử l y việc ghi nhận một đầu sách mới trên trang ThemSach.php khi
người dùng click button Thêm mới
<?php
if(isset($_REQUEST["btnThemMoi"]))
{
include_once("DataProvider.php");
// ghi nhan sach moi
$sql = "Insert into Book ( BookTitle, BookDesc, BookCatID, BookAuthor, BookPubID, BookYear, BookPrice ) values (";
$maSach = -1;
$sql = "select max(BookID) From Book";
$result = DataProvider::ExecuteQuery($sql);
if($result !=false) {
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$maSach = $row["max(BookID)"];
}
if (is_uploaded_file($_FILES['fileUploadHinhBia']['tmp_name'])) {
$fileName = $_FILES['fileUploadHinhBia']['name'];
$pos = strrpos( $fileName, "." );
$fileExtension = substr($fileName,$pos);
$hinhBia = "upload/" $maSach $fileExtension; move_uploaded_file($_FILES['fileUploadHinhBia']['tmp_name'], $hinhBia );
// cập nhật lại giá trị cột BookPic
$sql = "Update Book Set BookPic='" $hinhBia "' Where BookID=" $maSach;
DataProvider::ExecuteQuery($sql);
} }
?>
<!—chèn mã lệnh của file themSach.php ở trên >
Trang 26- Lấy mã sách từ trang xlTimSach.php ( $_REQUEST[“BookID”])
- Tạo câu query truy vấn thông tin của sách cần cập nhật
- Thực thi câu query vừa tạo, đưa các thông tin truy vấn được vào các control trên trang CapNhat.php
Xử l y sự kiện người dùng click vào button Cập nhật để hiệu chỉnh thông tin sách xuống CSDL