Tải bản đầy đủ (.pdf) (26 trang)

Bài 7 : PHP kết nối CSDL MySQLMôn : Lập trình và Thiết kế Web 1

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (823.48 KB, 26 trang )


KHOA 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



1
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007

Bà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 :


2
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
c- Bảng Publisher :




3
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
3. Tạo kết nối đến CSDL :
Do đa số các trang web đều kết nối đến CSDL, do đó ta sẽ đóng gói việc kết nối với
CSDL trong 1 class riêng để dễ dàng hơn trong việc sử dụng
Tạo file DataProvider.php
Lưu DataProvider.php trong thư mục C:\wamp\www\BookStoreOnline\
Khai báo class DataProvider trong DataProvider.php

<?php
class DataProvider
{
public static function ExecuteQuery($sql)
{
$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;
}
}
?>


Các trang nào cần sử dụng class DataProvider sử dụng khai báo sau:
<?php
include_once("DataProvider.php");
?>


4
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007




Để 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:





5
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
4. Sơ đồ hệ thống website cần xây dựng:



4.1. Trang chủ ( TrangChu.php )



TrangChu.php
TimSach .php DangNhap.php
xlTimSach.php
ThemSach.php xlXoa.php CapNhat.php

6
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
4.2. Trang đăng nhập ( DangNhap.php )


Mã lệnh

<html>
<head>
<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">
<tr>
<td>Tên đăng nhập</td>
<td>
<input type="text" name="txtTenDangNhap"/>
</td>
</tr>

<tr>
<td>Mật khẩu</td>
<td>
<input type="password" name="txtMatKhau" />
</td>
</tr>

<tr>
<td align="right">
<input type="submit" name="btnDangNhap" value="Đăng nhập" />
</td>
<td>


7
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
<input type="reset" name="btnLamLai" value="Làm lại" />
</td>

</tr>


<tr>
<td ><a href="#">Trở về trang chủ</a></td>
<td>&nbsp;</td>
</tr>

</table>
</form>
</body>
</html>

Bổ sung mã lệnh php xử lý việc đăng nhập trong trang DangNhap.php:

<html>
<head>
<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"];

$ketQuaDangNhap = false;

include_once("DataProvider.php");

$dsNguoiDung = DataProvider::ExecuteQuery("Select * From User");

if($dsNguoiDung != false)
{
while($row = mysql_fetch_array($dsNguoiDung,MYSQL_ASSOC))
{
if($tenDangNhap == $row["UserName"] &&
$matKhau == $row["Password"])
{
$ketQuaDangNhap = true;
}
}
}

if($ketQuaDangNhap == false)

8
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
{
?>

<form name="formDangnhap" method="post" action="DangNhap.php">
<table width="400" border="0">
<tr>
<td>Tên đăng nhập</td>
<td>
<input type="text" name="txtTenDangNhap" />
</td>
</tr>
<tr>

<td>Mật khẩu</td>
<td><input type="password" name="txtMatKhau" /></td>
</tr>
<tr>
<td align="right">
<input type="submit" name="btnDangNhap" value="Đăng nhập" /></td>
<td
<input type="reset" name="btnLamLai" value="Làm lại" /></td>
</tr>
<tr>
<td ><a href="#">Trở về trang chủ</a></td>
<td>&nbsp;</td>
</tr>
</table>
</form>

<?php
}
else
{
echo ("Xin chào " . $tenDangNhap);
?>
<a href="TrangChu.php" >Trở về trang chủ</a>

<?php
}
?>
</body>
</html>






9
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
4.3. Tìm sách (TimSach.php) & Xử lý tìm sách (xlTimsach.php)

1. Tìm sách



<html>
<head>
<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">

<tr>
<td>Tên sách</td>
<td><input type="text" name="txtTenSach" id="txtTenSach" /></td>
</tr>

<tr>
<td align="right">

<input type="submit" name="btnTim" id="btnTim" value="Tìm sách" />
</td>
<td>
<input type="reset" name="btnTimLai" value="Tìm lại" />
</td>
</tr>

<tr>

10
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
<td ><a href="#">Trở về trang chủ</a></td>
<td>&nbsp;</td>
</tr>

</table>

</form>
</body>
</html>



2. 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>
</head>


<body>
<p>
Kết quả tìm sách
</p>

<?php
// lấy tên sách tu trang TimKiem.php
$tenSach = $_REQUEST["txtTenSach"];

include_once("DataProvider.php");
$dsSach = DataProvider::ExecuteQuery("Select * From Book Where BookTitle like '%" . $tenSach . "%'");

if($dsSach != false)
{
if(mysql_num_rows($dsSach)>0)
{
?>
<table border="2" >
<tr>
<th width="50">STT</th>
<th width="50">Mã sách</th>
<th width="400">Tựa sách</th>
<th width="100">Giá tiền</th>
<th width="100">Xóa</th>
</tr>


1
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007

<?php

$stt = 1;
while($row = mysql_fetch_array($dsSach,MYSQL_ASSOC))
{
$maSach = $row["BookID"];
$tenSach = $row["BookTitle"];
$giaTien = $row["BookPrice"];

?>
<tr>
<td>
<?php
echo($stt);
$stt++;
?>
</td>
<td>
<?php
echo($maSach);

?>
</td>
<td>
<a href="CapNhatSach.php?BookID=<?php echo($maSach); ?>" >
<?php echo($tenSach); ?>
</a>
</td>
<td>
<?php echo($giaTien); ?>

</td>
<td>
<form name="form1" method="post" action="xlXoa.php">
<input type="hidden" name="BookIDDeleted" value="<?php echo($maSach); ?>" >

2
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
<input type="submit" name="btnXoa" value="Xóa" >

</form>
</td>
</tr>

<?php
} // end while

?>

</table>

<?php
} // end if(mysql_num_rows($dsSach)>0)
else
{
echo ("Không tìm thấy sách với tựa " . $tenSach);
}
} // end if ($dsSach != false )

?>
<a href="ThemSach.php" > Thêm một đầu sách mới </a>


</body>
</html>





3
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
3. Xử lý Phân trang xlTimsach.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " />transitional.dtd">
<html xmlns="
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<p>
Kết quả tìm sách
</p>
<?php
// Xử lý phân trang
$rowsPerPage = 20;
$pageNum = 1;

// if $_GET['page'] defined, use it as page number
if(isset($_GET['page']))
{

$pageNum = $_GET['page'];
}

$offset = ($pageNum - 1) * $rowsPerPage;

// lấy tên sách tu trang TimKiem.php
$tenSach = $_REQUEST["txtTenSach"];

include_once("DataProvider.php");

4
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
$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)
{
?>
<table border="2" >
<tr>
<th width="50">STT</th>
<th width="50">Mã sách</th>
<th width="400">Tựa sách</th>
<th width="100">Giá tiền</th>
<th width="100">Xóa</th>
</tr>
<?php


$stt = 1;
while($row = mysql_fetch_array($dsSach,MYSQL_ASSOC))
{
$maSach = $row["BookID"];
$tenSach = $row["BookTitle"];
$giaTien = $row["BookPrice"];
?>
<tr>
<td>
<?php
echo($stt);


5
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
$stt++;
?>
</td>
<td>
<?php echo($maSach);?>
</td>
<td>
<a href="CapNhatSach.php?BookID=<?php echo($maSach); ?>" >
<?php echo($tenSach); ?>
</a>
</td>
<td>
<?php echo($giaTien); ?>
</td>

<td>
<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" >
</form>
</td>
</tr>
<?php
} // end while
?>
</table>
<?php
// 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) ;

6
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
$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 = 1; $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;
}

} // end if(mysql_num_rows($dsSach)>0)
else
{
echo ("Không tìm thấy sách với tựa " . $tenSach);
}
} // end if ($dsSach != false )

?>


7
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
<a href="ThemSach.php" > Thêm một đầu sách mới </a>

</body>
</html>

4.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>
</head>

<body>
<?php
$bookIDDeleted = $_REQUEST["BookIDDeleted"];
include_once("DataProvider.php");

DataProvider::ExecuteQuery("Delete From Book Where BookID = " .
$bookIDDeleted);
?>

Đã xóa thành công cuốn sách có mã là <?php echo($bookIDDeleted); ?>
<br>
<a href="TimKiem.php" > Tiếp tục tìm kiếm </a>
<br>
<a href="TrangChu.php" > Trở về trang chủ </a>

</body>
</html>




1
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007

4.5. Trang Thêm một đầu sách mới ( ThemSach.php )



Mã lệnh

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Them mot cuon sach</title>
</head>

<body>
<h1>
<font color="blue"> Thêm một đầu sách mới </font>
</h1>
<form action="" method="post" enctype="multipart/form-data" name="form1">
<fieldset style="width:600px;">
<legend>Thông tin sách</legend>
<table width="600" border="0">
<tr>
<td width="167">Tựa sách</td>
<td width="423">
<input type="text" name="txtTenSach" />
</td>
</tr>

2
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007

<tr>
<td>Hình bìa</td>
<td><input type="file" name="fileUploadHinhBia" /></td>
</tr>

<tr>
<td>Nội dung tóm tắt</td>
<td><input type="text" name="txtNoiDungTomTat"/> </td>
</tr>

<tr>
<td>Thể loại</td>
<td>
<select name="cmbTheLoai" id="cmbTheLoai">

<?php
include_once("DataProvider.php");
$dsTheLoai = DataProvider::ExecuteQuery("Select * From Category");
if ( $dsTheLoai != false )
{
while ($row = mysql_fetch_array($dsTheLoai,MYSQL_ASSOC))
{
$maTheLoai = intval ($row["CategoryID"]);
$tenTheLoai = $row["CategoryName"];
?>
<option value="<?php echo($maTheLoai); ?>">
<?php echo($tenTheLoai); ?>
</option>
<?php
}

}
?>

</select>
</td>
</tr>

<tr>
<td>Danh sách tên tác giả</td>
<td><input type="text" name="txtTacGia" /></td>
</tr>

<tr>
<td>Nhà xuất bản</td>
<td>
<select name="cmbNhaXuatBan" id="cmbNhaXuatBan">
<?php
$dsNhaXuatBan = DataProvider::ExecuteQuery("Select * From Publisher");
if($dsNhaXuatBan != false)


3
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
{
while($row = mysql_fetch_array($dsNhaXuatBan,MYSQL_ASSOC))
{
$maNhaXuatBan = $row["PublisherID"];
$tenNhaXuatBan = $row["PublisherName"];
?>
<option value="<?php echo($maNhaXuatBan); ?>">

<?php echo($tenNhaXuatBan); ?>
</option>
<?php
}
}
?>
</select>
</td>
</tr>

<tr>
<td>Năm xuất bản</td>
<td><input type="text" name="txtNamXuatBan" /></td>
</tr>

<tr>
<td>Giá tiền</td>
<td><input type="text" name="txtGiaTien" /></td>
</tr>

<tr>
<td align="right">
<input type="submit" name="btnThemMoi" value="Thêm mới" />
</td>
<td>
nbsp;<input name="btnLamLai" type="reset" value="Làm lại" />
</td>
</tr>

</table>


</fieldset>
<a href="TrangChu.php" >Trở về trang chủ </a>

</form>
</body>
</html>



4
Bài 7 : PHP kế t nố i CSDL MySQL | 9/26/2007
Bổ 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 (";
$sql .= "'" . $_REQUEST["txtTenSach"] . "',";
$sql .= "'" . $_REQUEST["txtNoiDungTomTat"] . "',";
$sql .= $_REQUEST["cmbTheLoai"] . "," ;
$sql .= "'" . $_REQUEST["txtTacGia"] . "',";
$sql .= $_REQUEST["cmbNhaXuatBan"] . "," ;
$sql .= $_REQUEST["txtNamXuatBan"] . "," ;
$sql .= $_REQUEST["txtGiaTien"] . ")" ;


DataProvider::ExecuteQuery($sql);

$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)"];
}

// upload hinh bia cuốn sách
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 >


×