PHP - MySQL Giới thiệu

PHP (Hypertext Preprocessor) là ngôn ngữ script ở phía server. PHP hỗ trợ nhiều cơ sở dữ liệu (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, .) Tập tin PHP:  có thể chứa text, các thẻ HTML và các đoạn script; nhưng kết quả khi trả về trình duyệt là HTML  có phần mở rộng là ".php"

pdf77 trang | Chia sẻ: lylyngoc | Lượt xem: 1547 | Lượt tải: 1download
Bạn đang xem trước 20 trang tài liệu PHP - MySQL Giới thiệu, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
ThS Nguyễn Minh Vi BM Tin học – ĐH An Giang PHP - MySQL GIỚI THIỆU PHP  PHP (Hypertext Preprocessor) là ngôn ngữ script ở phía server.  PHP hỗ trợ nhiều cơ sở dữ liệu (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, ...)  Tập tin PHP:  có thể chứa text, các thẻ HTML và các đoạn script; nhưng kết quả khi trả về trình duyệt là HTML  có phần mở rộng là ".php" MySQL  MySQL là hệ quản trị cơ sở dữ liệu ở phía server  MySQL hỗ trợ SQL chuẩn PHP-MySQL  PHP kết hợp với MySQL có thể chạy được trên nhiều platform khác nhau  PHP và MySQL hoàn toàn miễn phí  Một số hệ thống mã nguồn mở phổ biến:  Quản trị nội dung, cổng thông tin: Joomla, Drupal, PHP-Nuke, …  Diễn đàn: phpBB, MyBB, SMF, …  Thương mại điện tử: ZenCart, OpenCart, …  Đào tạo trực tuyến: Moodle, …  Blog: Wordpress, … PHP-MySQL  Để bắt đầu với PHP và MySQL, ta cần chuẩn bị:  Cài đặt web server (IIS, Apache, …)  Cài PHP  Cài MySQL  Download:  Apache: httpd.apache.org/download.cgi  PHP: www.php.net/downloads.php  MySQL: www.mysql.com/downloads/index.html  Đơn giản hơn, có thể download các phần mềm WAMP, Vertrigo, XAMPP… ThS Nguyễn Minh Vi BM Tin học – ĐH An Giang PHP PHP Hypertext Preprocessor PHP cơ bản  Cú pháp  Biến  Kiểu dữ liệu  Toán tử  Cấu trúc điều khiển  Hàm  Ví dụ về xử lý form PHP cơ bản  Cú pháp  Biến  Kiểu dữ liệu  Toán tử  Cấu trúc điều khiển  Hàm  Ví dụ về xử lý form Cú pháp cơ bản  Một khối lệnh PHP có thể đặt bất cứ nơi nào trong trang web <?php // các câu lệnh ?>  Mỗi câu lệnh kết thúc bởi dấu ;  Chú thích  // một dòng  /* nhiều dòng */  Cú pháp gần giống C++, Perl Ví dụ <?php //In ra chuỗi “Hello World” echo "Hello World"; ?> PHP cơ bản  Cú pháp  Biến  Kiểu dữ liệu  Toán tử  Cấu trúc điều khiển  Hàm  Ví dụ về xử lý form Biến  Biến trong PHP không cần phải được khai báo trước, biến sẽ được tự động khai báo khi ta sử dụng nó  Tất cả các biến được bắt đầu bằng ký hiệu $  Tên biến:  có thể chứa các chữ cái, chữ số và dấu _  bắt đầu bởi ký tự chữ hoặc dấu _  không nên chứa khoảng trắng  Gán giá trị cho biến:  $var_name = value; Biến  Ví dụ: $myString  $4me  $_4you  Biến đặc biệt  $GLOBALS  $_COOKIE  $_GET  $_POST  $_REQUEST $_GET  Biến $_GET chứa một mảng tên biến và giá trị được gởi bởi phương thức HTTP GET.  Biến $_GET dùng để lấy giá trị từ form với phương thức truyền dữ liệu method="get".  Thông tin gửi từ form với phương thức GET được hiển thị trên thanh địa chỉ của trình duyệt, khối lượng dữ liệu gửi đi bị hạn chế $_POST  Biến $_POST chứa một mảng tên biến và giá trị được gởi bởi phương thức HTTP POST.  Biến $_POST dùng để lấy giá trị từ form với phương thức truyền dữ liệu method="post".  Thông tin gửi từ form bằng phương thức POST sẽ không được người dùng nhìn thấy, khối lượng dữ liệu truyền không hạn chế. $_REQUEST  chứa nội dung của các biến $_GET, $_POST, và $_COOKIE  thường dùng để lấy kết quả dữ liệu gửi từ form mà không cần quan tâm phương thức truyền dữ liệu là GET hay POST. Phạm vi biến  Biến trong một hàm thì là biến cục bộ đối với hàm đó  Biến khai báo trong một khối lệnh thì khả dụng trong suốt khối lệnh đó, nhưng không khả dụng trong hàm  Biến dùng trong một hàm mà khai báo là toàn cục thì nó tham chiếu đến biến toàn cục cùng tên  dùng $GLOBALS hoặc từ khóa global Phạm vi biến  Ví dụ <?php $a = 1; function printLocalVariable() { $a = 10; echo "Local variable = " . $a . ""; } function printGlobalVariable() { global $a; echo "Global variable = " . $a . ""; } printLocalVariable(); printGlobalVariable(); ?> PHP cơ bản  Cú pháp  Biến  Kiểu dữ liệu  Toán tử  Cấu trúc điều khiển  Hàm  Ví dụ về xử lý form Kiểu dữ liệu  Number  Boolean  String  Array  Object String  Một chuỗi có thể được dùng trực tiếp hoặc được chứa trong một biến  Toán tử:  Nối chuỗi: dấu .  Hàm:  strlen(): độ dài chuỗi  strpos(): tìm chuỗi con hoặc ký tự trong chuỗi String  Ví dụ <?php $txt1="Hello World"; $txt2="1234"; //Nối chuỗi echo $txt1 . " " . $txt2 . ""; //Tính độ dài chuỗi echo strlen("Hello world!") . ""; //Tìm vị trí chuỗi con echo strpos("Hello world!","world") . ""; ?> Array  Mảng chứa một hoặc nhiều giá trị trong một biến  Có các loại mảng:  Numeric array – phân biệt các giá trị bằng chỉ số  Associative array – phân biệt các giá trị bằng tên  Multidimensional array – chứa nhiều hơn một mảng Numeric Arrays  Numeric array phân biệt các phần tử mảng bằng chỉ số mảng  Tạo numeric array  Chỉ số được gán tự động  Chỉ số gán bằng tay $names = array("Peter","Quagmire","Joe"); $names[0] = "Peter"; $names[1] = "Quagmire"; $names[2] = "Joe"; Associative Arrays  Associative array phân biệt các phần tử bằng tên đi kèm với giá trị  ví dụ hoặc  Cách dùng $prices = array("pen"=>1000, "pencil"=>500); $prices['pen'] = 1000; $prices['pencil'] = 500; <?php $prices['pen'] = 1000; $prices['pencil'] = 500; echo "Pen costs " . $prices['pen'] . " VND."; ?> Multidimensional Arrays  Mảng đa chiều: Mỗi phần tử của mảng chính là một mảng con, mỗi phần tử trong mảng con có thể chứa một mảng con khác, … PHP cơ bản  Cú pháp  Biến  Kiểu dữ liệu  Toán tử  Cấu trúc điều khiển  Hàm  Ví dụ về xử lý form  Số học (Arithmetic)  Gán (Assignment)  So sánh (Comparison)  Logic (Logical) Toán tử Toán tử  Số học: Operator Description Example Result + Addition x=2 x+2 4 - Subtraction x=2 5-x 3 * Multiplication x=4 x*5 20 / Division 15/5 5/2 3 2.5 % Modulus (division remainder) 5%2 10%8 10%2 1 2 0 ++ Increment x=5 x++ x=6 -- Decrement x=5 x-- x=4 Toán tử  Gán: Operator Example Is The Same As = x=y x=y += x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y %= x%=y x=x%y Toán tử  So sánh: Operator Description Example == is equal to 5==8 returns false != is not equal 5!=8 returns true > is greater than 5>8 returns false < is less than 5<8 returns true >= is greater than or equal to 5>=8 returns false <= is less than or equal to 5<=8 returns true Toán tử  Logic: Operator Description Example && and x=6 y=3 (x 1) returns true || or x=6 y=3 (x==5 || y==5) returns false ! not x=6 y=3 !(x==y) returns true PHP cơ bản  Cú pháp  Biến  Kiểu dữ liệu  Toán tử  Cấu trúc điều khiển  Hàm  Ví dụ về xử lý form Câu lệnh rẽ nhánh  if … else  thực thi một khối lệnh nếu điều kiện đúng, thực thi một khối lệnh khác nếu điều kiện sai if (condition) code to be executed if condition is true; else code to be executed if condition is false; Câu lệnh rẽ nhánh  switch … case  chọn một trong nhiều khối lệnh để thực thi switch (expression) { case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; } Câu lệnh lặp  while  lặp lại (thực thi) một khối lệnh khi điều kiện vẫn còn đúng  do...while  thực thi một khối lệnh (ít nhất) một lần, lặp lại khi điều kiện vẫn còn đúng while (condition) code to be executed; do { code to be executed; } while (condition); Câu lệnh lặp  For  lặp một khối lệnh với số lần xác định  Foreach  thực thi một khối lệnh đối với từng phần tử trong mảng for (initialization; condition; increment) { code to be executed; } foreach (array as value) { code to be executed; } PHP cơ bản  Cú pháp  Biến  Kiểu dữ liệu  Toán tử  Cấu trúc điều khiển  Hàm  Ví dụ về xử lý form Hàm  Khai báo hàm với từ khóa function  Tên hàm có thể bắt đầu bằng một ký tự hoặc dấu gạch dưới, không bắt đầu bởi số  Khối lệnh trong hàm được bao bởi cặp dấu ngoặc nhọn {} Hàm  Hàm có tham số <?php function writeName($name){ echo "Your name is " . $name; } writeName("Vi"); ?> Hàm  Hàm trả về giá trị <?php function add($x,$y){ $total = $x + $y; return $total; } echo "1 + 16 = " . add(1,16); ?> PHP cơ bản  Cú pháp  Biến  Kiểu dữ liệu  Toán tử  Cấu trúc điều khiển  Hàm  Ví dụ về xử lý form Xử lý form Name: Age: Welcome . You are years old. Welcome.php Xử lý form Minh 22 ThS Nguyễn Minh Vi BM Tin học – ĐH An Giang MySQL Kết nối đến CSDL MySQL  Cú pháp: mysql_connect( servername, username, password); Parameter Description servername Optional. Specifies the server to connect to. Default value is "localhost:3306" username Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process password Optional. Specifies the password to log in with. Default is "" Đóng kết nối  Cú pháp:  VD: <?php $con = mysql_connect("localhost","nmvi","xTy"); if (!$con) { die('Could not connect: ' . mysql_error()); } // some code mysql_close($con); ?> mysql_close(connection); Tạo mới  Tạo CSDL  Tạo bảng CREATE DATABASE database_name CREATE TABLE table_name ( column_name1 data_type, column_name2 data_type, column_name3 data_type, … ) <?php $con = mysql_connect("localhost",“nmvi",“xTy"); if (!$con) { die('Could not connect: ' . mysql_error()); } // Create database if (mysql_query("CREATE DATABASE my_db",$con)) { echo "Database created"; } else { echo "Error creating database: " . mysql_error(); } // Create table in my_db database mysql_select_db("my_db", $con); $sql = "CREATE TABLE person ( ID int NOT NULL AUTO_INCREMENT, FirstName varchar(15), LastName varchar(15), Age int, PRIMARY KEY(ID) )"; mysql_query($sql,$con); mysql_close($con); ?> VD: Chèn Chèn dữ liệu vào một bảng trong CSDL  Cú pháp hoặc INSERT INTO table_name VALUES (value1, value2,....); INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....) Truy vấn Chọn dữ liệu từ CSDL  Cú pháp SELECT column_name(s) FROM table_name Truy vấn - Mệnh đề Where  Chỉ chọn các dữ liệu phù hợp với điều kiện  Cú pháp  Toán tử sử dụng trong mệnh đề WHERE  =, !=, >, >=, <, <=  LIKE, BETWEEN SELECT column FROM table WHERE column operator value Truy vấn - Mệnh đề Order by  Sắp xếp dữ liệu truy vấn được  Cú pháp  Mặc định là sắp tăng (ASC) SELECT column_name(s) FROM table_name ORDER BY column_name DESC <?php $con = mysql_connect("localhost","nmvi","xTy"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("my_db", $con); $result = mysql_query("SELECT * FROM person ORDER BY age"); while($row = mysql_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName'] . " " . $row['Age'] . ""; } mysql_close($con); ?> VD: Cập nhật Chỉnh sửa dữ liệu trong bảng CSDL  Cú pháp UPDATE table_name SET column_name = new_value WHERE column_name = some_value Xóa Xóa mẩu tin trong bảng CSDL  Cú pháp DELETE FROM table_name WHERE column_name = some_value ThS Nguyễn Minh Vi BM Tin học – ĐH An Giang PHP NÂNG CAO PHP advance  Cookie  Session  Email ThS Nguyễn Minh Vi BM Tin học – ĐH An Giang PHP Cookie Cookie  A cookie is a small file that the server embeds on the user's computer  With PHP, you can both create and retrieve cookie values  Cookies are part of the HTTP header, so cookies must be set before any output is sent to the browser Set Cookie  Set cookie  place before the tag  Parameter  name: required  value: this value is stored on the clients computer  expire: the time the cookie expires, in seconds  path: the path on the server in which the cookie will be available on  domain: the domain that the cookie is available  secure: the cookie will be set if a secure connection exists (default is FALSE) setcookie(name, value, expire, path, domain, secure); Ex <?php $value = 'something'; setcookie("TestCookie", $value); // expire in 1 hour setcookie("TestCookie", $value, time()+3600); ?> Retrieve a cookie value  Use the PHP $_COOKIE variable  Ex: <?php // Print an individual cookie echo $_COOKIE["TestCookie"]; // Another way to debug/test is to view all cookies print_r($_COOKIE); ?> Delete a cookie  Assure that the expiration date is in the past <?php // set the expiration date to one hour ago setcookie("TestCookie", "", time() - 3600); ?> ThS Nguyễn Minh Vi BM Tin học – ĐH An Giang PHP Session Session  A PHP session allowing you to store user information on the server for later use, session information is temporary and will be deleted after the user has left the website.  Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. Starting a PHP Session  The session_start() function  place before the tag <?php session_start(); ?> Storing a Session Variable  Use the PHP $_SESSION variable <?php session_start(); if (isset($_SESSION['views'])) $_SESSION['views'] = $_SESSION['views'] + 1; else $_SESSION['views'] = 1; //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> Destroying a Session  The unset() function is used to free the specified session variable  The session_destroy() function is used to destroy the session completely <?php unset($_SESSION['views']); ?> <?php session_destroy(); ?> ThS Nguyễn Minh Vi BM Tin học – ĐH An Giang PHP Email mail() function  Syntax  Parameters  to: (required) specifies the receiver / receivers of the email  subject: (required) specifies the subject of the email  message: (required) defines the message to be sent mail(to,subject,message,headers,parameters) mail() function  Parameters (cont.)  headers (optional) specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n)  parameters (optional) specifies an additional parameter to the sendmail program Example <?php $to = "bibi@gmail.com"; $subject = "Gui mail bang PHP"; $message = "Day la mot email don gian, chi chua text."; $headers = "From: bobo@gmail.com"; if (mail($to,$subject,$message,$headers)) echo "Da gui."; else echo "Khong gui duoc"; ?> more...  To send mail to multiple recipients, using comma  To send HTML mail, set the Content-type header $headers = 'Content-type: text/html; charset=utf-8' $to = 'bibi@gmail.com' . ', '; $to .= 'bobo@gmail.com'; Configuration (php.ini) Name Default SMTP "localhost" smtp_port "25" sendmail_from NULL sendmail_path NULL Configuration  SMTP  DNS name or IP address of the SMTP server PHP should use for mail sent with the mail() function.  smtp_port  Number of the port to connect to the server specified with the SMTP setting when sending mail with mail(); defaults to 25 (available since PHP 4.3.0).