1 / 22

Chương 3: PHP và MySQL

0- Một số lưu ý về MySQL 1. Kết nối đến Database Server MySQL 2. Truy cập CSDL và thực thi câu lệnh SQL 3. Tiếng Việt trong MySQL, PHP 4. Phân trang trong PHP 5- Class for DBManagement Các chủ đề khác như Đăng ký tín chỉ, E-commerce, Blog, Wibsite báo chí … sẽ trình bày ở chương sau.

onan
Download Presentation

Chương 3: PHP và MySQL

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 0- Một số lưu ý về MySQL 1. Kết nối đến Database Server MySQL 2. Truy cập CSDL và thực thi câu lệnh SQL 3. Tiếng Việt trong MySQL, PHP 4. Phân trang trong PHP 5- Class for DBManagement Các chủ đề khác như Đăng ký tín chỉ, E-commerce, Blog, Wibsite báo chí … sẽ trình bày ở chương sau. Chương 3:PHP và MySQL nutshell : bản tóm tắt ngắn gọn

  2. 0- Một số lưu ý về MySQL • - Hầu hết câu lệnh của ANSI SQL đêu tương thích trong MySQL, tuy nhiên câu lệnh Select mạnh hơn Select top của SQL Server: • Select .. From .. Where …limit start, total • Trong đó 0 ≤ start ≤ mysql_num_rows($rs) • Một số hàm trong MySQL • Các hàm tổng hợp dữ liệu: avg, count, sum, min. max • Các hàm riêng của MySQL: first, last, ucase, lcase, mid, now, len, round, format • Các dùng các hàm :select Hàm() as tênCột, … • Các vấn đề khác đã trình bày ở chương trước (Hệ qtcsdl MySQL)

  3. I- Kết nối đến database server • 1- Cú pháp • mysql_connect(server_name,username,password); • Đối với localhost, dù webserver có PORT là 81 vẫn không ghi thêm port, port mặc định của database server MySQL là 3306. • Các phong cách sử dụng : • 1- $con=mysql_connect(svn,usr,pss) or die(“Error :”.mysql_error()); • 2- $con=mysql_connect(svn,usr,pss); • if(!$con) {die(“Error :”.mysql_error(); //có thể thay đổi message} • else{ // truy cập database } • Ví dụ : • $con=mysql_connect(“localhost”,”root”,””) or die(“Error :”.mysql_error()); • Lưu ý: Hãy nhận xét về hàm die() và các sử dụng if…else ở đây!

  4. II- Thực thi câu lệnh SQL • 1- Truy cập CSDL • mysql_select_db(“database name", $con); • với $con được trả về trong mysql_connect() đã thành công trước đó. • 2- Thực thi câu lệnh SQL • mysql_query(“SQL_Statement”); • Tùy theo câu lệnh SQL mà ta có kết quả trả về của hàm mysql_query() • mà ta có mã PHP xử lý tương ứng. • + Câu lệnh Select : trả về mảng các record • + Các câu lệnh khác : true/false tùy theo sự thành công hay không • a)Câu lệnh SQL : Select… • $strSQL=“Select * from table_name”;//nếu câu lệnh SQL dài, phức tạp. • $result = mysql_quer($strSQL,[$con]); • if($result) { trích xuất dữ liệu trong mảng $result;} // !? • else {echo “Records not found!”;}

  5. b) Câu lệnh SQL : Create Database • $result=mysql_query("CREATE DATABASE database_name",$con ); • if($result) {echo “Database created!”;} • else {echo “Could’nt create database,” .mysql_error();} • Tuy nhiên, để đảm bảo các field kiểu char có thể dữ liệu theo mã UTF-8 thì cần thay đổi câu lệnh SQL: • $strSQL="CREATE DATABASE VD2”; • $strSQL+= “DEFAULT CHARACTER SET utf8COLLATE utf8_unicode_ci"; • $result=mysql_query($strSQL,$con ); • if($result) {echo “Database created!”;} • else {echo “Could’nt create database,”.mysql_error();} • - Ta thường tạo CSDL thông qua một công cụ riêng, ít khi sử dụng câu lệnh như trên. Tuy nhiên, tạo table lại hay sử dụng. • - Collate: đối chiếu, kiểm tra thứ tự (trang).

  6. c- Câu lệnh SQL: Create table • $sql = "CREATE TABLE table_name ( • field_name data_type[(length)] constraint,… • ) ENGINE = MyISAM CHARACTER SET utf8COLLATE utf8_unicode_ci"; • Nến storage engine là • InnoDB : cho phép kiểm soát transaction và referential constraints • MyISAM: không có 2 khả năng trên, nhưng tốc độ xử lý nhanh hơn, đây là kiểu storage mặc định. • Ví dụ : • $sql=“Create table SV (Ma varchar(11) NOT NULL ,”;$sql+=HoTen varchar(30) not null , primary key(Ma)”; • $sql+=“) engine = MyISAM” ; • $result = mysql_query($sql,$con); • if(!$result) {echo “Error”.mysql_error();} • else { // mã PHP phù hợp}

  7. ISAM = Indexed Sequential Access Method and is essentially a flat file (for those DBAs who can remember, think Btrieve, or B-Tree). It's a very old technology - but don't let that put you off using it. Because it's a flat file (more on that later), it is not relational, and thus is not an RDBMS, and thus is more appropriate in some situations.InnoDB is the full RDBMS like you are most likely familiar with. MyISAM can appear to be relational through another layer added on top that maintains your links, logic and referential integrity. ISAM is brilliant if you have a LOT of records (like, 20 million), and the records are mostly stand-alone (i.e. you don't need to do lots of links to retrieve associated data). It relies VERY heavilly on indexes and if you don't have the right index, be prepared for very very long query times. Case in point: We had a Btrieve ISAM table with 20M+ records and to do a retrieve and filter data based on an accurate index was almost instant. Using the wrong index was literally 15 minutes.InnoDB is great for if you have a lot of relational links. Table A references a field in Table B, which references Table C and D. InnoDB can fetch these records using all sorts of nice joining methods (hash joins, etc), whereas an ISAM database would have to run multiple sub-queries for every single row and match the records manually. From: http://serverfault.com/questions/54897/what-is-the-difference-between-innodb-and-myisam

  8. d- Câu lệnh Insert, Update • $sql=“Insert into table_name(field_list) values(value_list); • $result=mysql_query($sql); • if(!$result) {echo mysql_error(); // xử lý tiếp;} • else { //xử lý …} • Việc sử dụng câu lệnh Upadte cũng tương tự • Lỗi xảy ra nếu vi phạm một trong các ràng buộc toàn vẹn dữ liệu. • Sử dụng hàm die() một cách hợp lý • Sử dụng transaction để điều khiển mạch chương trình. Xem bài đọc thêm PHP trên trang web của giảng viên

  9. e- Câu lệnh SQL: Select… • $sql = “Select …..”; • $result = mysql_query($sql); • if(!$result) { echo “Record not found!”; } • else { • while($row = mysql_fetch_array($result)){   echo $row[‘firstField'] . " " . $row[‘secondField'];   echo "<br />";} • } // else • mysql_close($con); // đóng kết nối • Câu lệnh Select … from … where … limit start, total trong MySQL • Trong đó start: là bắt đầu từ record số start (>=0), Record đầu tiên thứ tự là 0 • Total : là tổng số record được hiển thị. Đây là đặc điểm riêng của MySQL • fetch : nạp vào, tìm và nạp vào, $row là một mảng với key là fieldname • Chúng ta còn phương pháp khác duyệt “tập các record”, xem trang sau. (1)

  10. Hàm mysql_fetch_array Cú pháp: mysql_fetch_array(data [, array_type]); Array_type có thể là: MySQL_Assoc : mảng kết hợp, key của mảng là field_name MySQL_Num : key của mảng là chỉ số MySQL_Both : cả hai khả năng trên, đây là kiểu mặc định. Vì không khai báo array_type, tức là MySQL_Both, do vậy (1) có thể: while($row = mysql_fetch_array($result)){   echo $row[0] . " " . $row[1];   echo "<br />";}

  11. III- Tiếng Việt trong PHP • Phần không sử dụng CSDL MySQL, phải đảm bảo: • Lưu tệp với mã UTF-8 (*) • Khai báo trong phần head • <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> • Phần sử dụng CSDL MySQL, phải đảm bảo: • Khai báo câu lệnh mysql_query(“SET NAMES ‘utf8’”) trước câu lệnh • mysql_query($sql) với $sql là một câu lệnh Select. Ví dụ: • $sql = “Select …..”; • mysql_query(“SET NAMES ‘utf8’”); (*) • $result = mysql_query($sql); • if(!$result) { echo “Record not found!”; } • else { • while($row = mysql_fetch_array($result)){   echo $row[‘firstField'] . " " .$row[‘secondField'].”<br>”;} • }

  12. IV- Phân trang trong PHP •  Kỹ thuật cơ bản dựa trên câu lệnh Select …limit start, total • Mỗi trang sẽ hiển thị total records, bắt đầu từ reocord thứ start • Record đầu tiên có thứ tự là 0. •  Có nhiều phương pháp xây dựng các link để điều khiển trang • Pre12345Next • Giả sử test.php là trang PHP có chức năng hiển thị trang thứ $I với số record là $PageSize, tùy theo $i mà xác định $start để xây dựng câu • lệnh Select cho từng lựa chọn • Phương pháp ưa thích được lựa chọn là sử dụng : • $start : vị trí record bắt đầu của trang hiện tại • $prev : vị trí bắt đầu cho trang liền trước trang hiện tại (link PREV) • $next :vị trí bắt đầu cho trang liền sau trang hiện tại (link NEXT)

  13. Trong ứng dụng này, ta có 4 module: •  Connect.inc có chức năng kết nối đến CSDL, sử dụng các hàm: • mysql_connect() và msql_select_db() • Trong lập trình CSDL, module này cần thiết kế tốt và lưu dưới một file .inc riêng, trang nào cần thì include vào • Init.inc có chức năng khởi tạo các biến chung để điều khiển link • Test.phplà trang chính,có chức năng hiển thị nội dung trang với các record bắt đầu từ $start đến ($start+$pagesize-1), bao gồm Connect.inc, Init.inc và Link.inc • Link.inc có chức năng tạo ra các liên kết dạng Prev1234Next Trong nhiều chương trình, LTV xây dựng hẵn một Class để truy cập CSDL. Sinh viên xem trong phần Bài đọc thêm PHP trên website của giảng viên về nội dung này.

  14. Tệp Connect.inc <?php $servername='localhost'; // Server Name hay địa chỉ IP dều được $dbusername='root'; // Login user name $dbpassword='root'; // User’s password $dbname='paging'; // Tên CSDL MySQL cần thiết connecttodb($servername,$dbname,$dbusername,$dbpassword); function connectdb($svn,$dbn,$dbu,$db){ global $con; //$con sẽ dùng trong một số câu lệnhmsql_ $con=mysql_connect ("$svn","$dbu","$dbp"); if(!$con){die(“Không thể kết nối đến MySQL Server");} mysql_select_db("$dbn",$con) or die (“Không thể mở CSDL, lý do: ".mysql_error()); } ?>

  15. Tệp Init.inc <?php $pagesize=15; // Mỗi trang hiển thị 15 record, trừ trang cuối có thế ít hơn $start=$_GET['start']; $start=($start-0); // chuyển $start thành số tự nhiên //Ban dau khong GET nen $start="" =>($start-0)=0; $back = $start - $pagesize; $next = $start + $pagesize; $query="select * from Student"; $result=mysql_query($query); $totalRecords=mysql_num_rows($result); // Total records of recordset echo "Total records $totalRecords <br>"; ?>

  16. Tệp Test.php • <?php • include("config.php"); • include("init.inc"); • mysql_query("SET NAMES 'utf8'"); • $query="select * from Student limit $start,$pagesize"; • $result=mysql_query($query); • $i=1; • while($row = mysql_fetch_array($result)){ • echo $i."&nbsp;&nbsp;".$row[1]."<br>"; $i++;} • include("link.inc"); • mysql_close($link); • ?>

  17. Tệp Link.inc <?php echo "<hr>"; if($totalRecords > $pagesize ){ if($back >=0) {echo "<a href='test.php?start=$back'>Prev</a>"; } $i=0; // theo dõi số thứ tự các record $j=1; // theo số thứ tự của trang để tạo liên kết for($i=0;$i < $totalRecords;$i+=$pagesize){ if($i <> $start){echo " <a href='test.php?start=$i'>$j</a> "; } else { echo $j;} $j=$j+1; } if($next < $totalRecords) {echo "<a href='test.php?start=$next'>Next</a>";} } ?> DEMO (với mã nguồn này)MORE

  18. Tóm tắt : sử dụng MySQL trong PHP • ob_start(); // turn on ouput buffering • $con=mysql_connect($host,$user,$pass); • mysql_select_db($dbname,$con); • Execute Query :mysql_query($sql [,$con]) • Select => $result=mysql_query($sql ,$con) • while($row=mysql_fetch_array($result)) { //output } • Other => $result=mysql_query($sql); • echo mysql_affected_row() • mysql_free_result($result); • mysql_close($con); • ob_end_flush(); // send data to client and turn off ouput buffering • //ob_end_clean(); // erase buffer and turn off buffering • Lưu ý : các hàm trên trả về giá trị boolean, nhớ kiểm tra lỗi, die()…

  19. Class đơn giản để quản lý CSDL (Hiệu chỉnh từ nguồn của PHP Việt Nam) Tệp 07SPT.class.php, dùng include vào trang cần CSDL <?php class SPT{ private $connection = NULL; private $result = NULL; public function connect($host, $user, $pass, $database) { $this->connection = mysql_connect($host, $user, $pass,TRUE); mysql_select_db($database, $this->connection); } public function disconnect() { if (is_resource($this->connection)) { mysql_close($this->connection); } } … xem tiếp slide sau, hàm is_resource($biến) kiểm tra $biến có phải recordset.

  20. public function query($query) { mysql_query("SET NAMES 'utf8'"); // lấy dữ liệu với mã UTF-8 if (is_resource($this->connection)) { if (is_resource($this->result)) { mysql_free_result($this->result);} $this->result = mysql_query($query,$this->connection); } } public function fetchRow() { if (is_resource($this->result)) { $row = mysql_fetch_assoc($this->result); // dùng mysql_fetch_assoc tốt hơn mysql_fetch_array if (is_array($row)) {return $row;} else {return FALSE;} } } } // end class ?>

  21. Tệp Index.php (có thể đặt tên khác) <?php // Hãy tạo CSDL SV có table SV(MaSV,HoTen,DiaChi) include("07SPT.CLASS.PHP"); $db = new SPT; $db->connect('localhost', 'root', 'root', 'SV'); $db->query('SELECT * FROM SV'); $st="<table>”; $i=1; while ($row = $db->fetchRow()) { $st.="<tr><td>".$i."</td><td>“.$row["HoTen"]."</td>”; $st.=“<td>".$row["DiaChi"]."</td></tr>"; $i++; } $st.="</table>"; echo $st; $db->disconnect(); ?>

  22. Thank you! http://ndtfit.brinkster.net

More Related