Bài giảng PHP - MySQL (Nguyễn Minh Vi)

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 | Chuyên mục: PHP | Chia sẻ: dkS00TYs | Lượt xem: 1815 | Lượt tải: 1download
Tóm tắt nội dung Bài giảng PHP - MySQL (Nguyễn Minh Vi), để xem tài liệu hoàn chỉnh bạn click vào nút "TẢI VỀ" ở trên
000;
$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). 

File đính kèm:

  • pdfBài giảng PHP - MySQL (Nguyễn Minh Vi).pdf
Tài liệu liên quan