Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Ni dung trnh by
I. II. III.
I.
II. III. IV.
V.
VI. VII. VIII. IX.
I. Lm quen vi PHP
I.1. PHP l g? I.2. Lch s pht trin ca PHP I.3. L do chn PHP I.4. Zend Engine I.5. Ci t PHP I.6. Chng trnh PHP u tin I.7. Cc IDE cho PHP
I.1. PHP l g?
PHP c pht trin t ngn ng kch bn (script) vi mc ch xy dng trang Web c nhn (Personal Home Page). Sau c pht trin thnh mt ngn ng hon chnh v c a chung trn ton th gii trong vic pht trin cc ng dng Web based Theo NetCraft:
PHP (PHP: Hypertext Perprocessor) l ngn ng kch bn lp trnh pha my ch (server-side) ph bin nht th gii. PHP thng hot ng theo th t sau:
Ngi dng gi yu cu ln my ch My ch x l yu cu (Thng dch m PHP v chy chng trnh, m PHP c th truy xut CSDL, to hnh nh, c ghi file, tng tc vi my ch khc...) My ch gi d liu v cho ngi dng (thng l di dng HTML)
Phin bn u tin ca PHP c pht trin nm 1994, bao gm cc macro cho trang Web c nhn (Personal Home Page) Sau , PHP c pht trin thm mt s chc nng mi gi l Form Interpreter (PHP/FI) v c c s quan tm ln t pha cng ng Phin bn tip theo, PHP3, c vit li bi mt nhm cc lp trnh vin (Zeev Suraski, Andi Gutmans). PHP3 c b sung thm mt s tnh nng v cc c php ngn ng khc, tr thnh ngn ng kch bn pha my ch c a chung nht
Khi s dng PHP, ngi dng s c c tc nhanh hn nhiu so vi cc ngn ng kch bn khc, bi PHP l phn mm m ngun m, c h tr bi nhiu lp trnh vin gii, c s lng ngi dng ng o. Ngoi ra PHP chy c trn nhiu h iu hnh khc nhau
PHP cho php bn tch phn HTML code v phn script, do c th c lp gia cng vic pht trin m v thit k. iu ny va gip lp trnh vin d dng hn va c th lm cho chng trnh mm do hn trong vic thay i giao din PHP khng ch l phn mm m ngun m m cn thc s min ph (k c khi bn s dng cho mc ch thng mi) Do l phn mm m ngun m, cc li (bug) ca PHP c cng khai v nhanh chng c sa cha bi nhiu chuyn gia
Tc
Nh vo sc mnh ca Zend Engine, khi so snh PHP vi ASP, c th thy PHP vt hn mt s test, vt tri tc bin dch. PHP c thit k chy trn nhiu nn tng khc nhau, c th lm vic vi nhiu phn mm my ch, c s d liu (v d: bn c th pht trin d n trn UNIX, sau chuyn sang NT m khng gp phi bt c vn g)
Tnh kh chuyn
Zend l scripting engine nm bn trong PHP Zend Engine thc s l s ci tin ng k. Hu ht cc on m vit trn PHP3 u c th chy trn PHP4 vi tc tng gp 200 ln
I.5. Ci t PHP
Bn c th tm phin bn mi nht ca PHP ti a ch http://www.php.net PHP l phn mm m ngun m, bn c th download c m ngun ca PHP Bn c th tm ti liu tham kho ca PHP ti a ch http://www.php.net/manual
Control Panel/Add Remove Programs/Add Remove Window Components Bt Internet Information Services Download PHP Installer (Windows Binaries) t http://www.php.net/downloads.php Ci t PHP (chn server IIS) Download Apache ti http://httpd.apache.org/ Ci t Apache
Ci t Apache
Download bn PHP zip package (Window Binaries) Gii nn vo th mc C:\PHP Sa file conf/httpd.conf, thm vo ni dung sau
ScriptAlias /php/ "c:/php/" AddType application/x-httpd-php .php Action application/x-httpd-php "/php/php.exe"
Ch : fake phi bt u bng / nu fake kt thc bng / th realname cng phi kt thc bng /
Chng trnh u tin (bn c th son bng bt k trnh son tho vn bn no)
<?php echo("Hello world"); ?> Lu file di tn hello.php ti c:\inetpub\wwwroot\php (IIS) hoc trong th mc ng vi Alias va to ra Ti trnh duyt, nhp vo a ch http://localhost/php/hello.php
Khi chng trnh PHP Tag style Chun Dng rt gn ASP Script tags Start Tag <?php <? <% End Tag ?> ?> %>
II. PHP Cn bn
II.1. Bin, kiu v hng II.2. Ton t v biu thc II.3. Cc cu lnh iu khin II.4. Hm II.5. Lp & i tng II.6. Tham chiu (reference)
II.1.1.1. Tn bin
<?php $var = "Bob"; $Var = "Joe"; echo "$var, $Var"; // outputs "Bob, Joe" $4site = 'not yet'; // invalid; starts with a number $_4site = 'not yet'; // valid; starts with an underscore $tyte = 'mansikka'; // valid; '' is (Extended) ASCII 228. ?>
Bin c k hiu bi k t $ Tn bin phi c bt u bi 1 ch ci hoc k t gch chn Tn bin khng cha cc du v k t cch
function test() { global $foo; return $foo; } $bar = &test(); echo($bar); ?>
// Invalid.
II.1.2. Kiu
Cc kiu n
II.1.2.1. boolean II.1.2.2. integer II.1.2.3. float II.1.2.4. string
Cc kiu phc
II.1.2.5. array II.1.2.6. object
Cc kiu c bit
II.1.2.7. resource II.1.2.8. NULL
<?php $a=10000000; var_dump($a); echo("<br>"); $a=100000000; var_dump($a); echo("<br>"); $a=1000000000; var_dump($a); echo("<br>"); $a=10000000000; var_dump($a); echo("<br>"); ?>
String trong PHP l mt chui cc k t 1 byte. PHP khng h tr Unicode, lm vic vi Unicode bn phi s dng UTF8 vi cc hm utf8_encode() utf8_decode() String ca PHP h tr chiu di rt ln (?) Trong PHP, string c xc nh theo 3 cch
Du nhy n (single quote) Du nhy kp (double quote) Heredoc Truyn kiu n gin Truyn kiu phc
echo 'You can also have embedded newlines in strings this way as it is okay to do'; // Outputs: Arnold once said: "I'll be back" echo 'Arnold once said: "I\'ll be back"'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\\*.*?'; // Outputs: You deleted C:\*.*? echo 'You deleted C:\*.*?'; // Outputs: This will not expand: \n a newline echo 'This will not expand: \n a newline'; // Outputs: Variables do not $expand $either echo 'Variables do not $expand $either'; ?>
Kiu du nhy kp: kiu ny ging vi kiu du nhy n nhng c nhiu h tr cho cc k t c bit hn
echo($str); ?>
Truyn bin kiu phc (truyn bin kiu mng vo string) s cp n phn mng
?>
Kiu Array ca PHP thc s l kiu nh x (map) c th t. Tc l kiu d liu gm cc cp kha (key) v gi tr (value). Vi kiu mng ny, bn c th s dng nh mt mng thun ty (vector), hay dng cho cc kiu d liu collection, stack, queue, tree...
?>
II.1.3. Hng
nh ngha hng bng cch s dng hm define() Phm vi ca hng l ton cc (global) Ch c cc dng d liu n gin (boolean, interger, float, string)
Nu tn hng cha c nh ngha, PHP gi thit rng bn ang s dng 1 hng cha gi tr l 1 string (chnh l tn ca hng )
xc nh mt hng c nh ngha hay cha, bn c th s dng hm defined
<?php define("CONSTANT", "Hello world."); echo CONSTANT; // outputs "Hello world." echo Constant; // outputs "Constant" and issues a notice. echo defined("Constant"); echo defined("CONSTANT"); ?>
Cc hng c nh ngha trc (cc hng ny thng c s dng phc v qu trnh debug
Tn hng __LINE__ __FILE__ M t Th t dng hin ti trong file ng dn y ca file hin ti
__FUNCTION__
__CLASS__ __METHOD__
Tn hm hin ti
Tn lp hin ti Tn phng thc hin ti ca lp
II.2.2. Ton t s hc
Example $a + $b $a - $b $a * $b $a / $b $a % $b Name Addition Subtraction Multiplication Division Modulus Result Sum of $a and $b. Difference of $a and $b. Product of $a and $b. Quotient of $a and $b. Remainder of $a divided by $b.
II.2.3. Ton t gn
Ton t gn (=) cho php bn gn mt biu thc (v phi) cho 1 bin (v tri) Ton t gn tr v gi tr ca biu thc v phi, do c th dng nhiu php gn lin tip nhau Ngoi ra, cn c cc php ton gi l php ton kt hp cho hu ht cc ton t s hc thay i gi tr 1 bin theo php ton s hc (+=, -=, *=, /=, .= ...) <?php $a = 4; echo "$a\n"; $a = $b = $c = 10; echo "$a,$b,$c\n"; $a = ($b=4) + 5; echo "$a,$b\n"; $a .= "quang"; echo "$a\n"; $a = ($b+=10) + 2; echo "$a"; ?>
// Outputs '5' // Outputs the Backspace character (ascii 8) // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8 echo "hallo"^"hello"; // Outputs the ascii values #0 #4 #0 #0 #0 // 'a' ^ 'e' = #4 ?>
$a < $b
$a > $b $a <= $b
Less than
Greater than Less than or equal to Greater than or equal to
$a >= $b
Ton t iu khin li (@) dng t trc cc hm, biu thc. Khi tt c cc thng bo li trong hm, biu thc b b qua <?php $b = @file("a adf a") or die("Khong the mo file"); ?>
Name
And Or Xor Not And
Result
TRUE if both $a and $b are TRUE. TRUE if either $a or $b is TRUE. TRUE if either $a or $b is TRUE, but not both. TRUE if $a is not TRUE. TRUE if both $a and $b are TRUE.
$a || $b
Or
<?php $a = "Hello "; $b = $a . "World!"; // now $b contains "Hello World!" $a = "Hello "; $a .= "World!"; ?> // now $a contains "Hello World!
if ($a > $b) echo "a is } elseif ($a echo "a is } else { echo "a is } ?>
II.4. Hm
II.4.1. Hm t nh ngha (user-defined) II.4.2. Truyn tham s II.4.3. Gi tr tr v II.4.4. Bin hm
II.4.3. Gi tr tr v
tr v gi tr ca hm, s dng lnh return. C th s dng bt c kiu no trong gi tr tr v ca hm (k c mng v i tng)
<?php function square ($num) { return $num * $num; } echo square (4); // outputs '16'. function small_numbers() { return array (0, 1, 2); } list ($zero, $one, $two) = small_numbers(); function &returns_reference() { return $someref; } $newref =& returns_reference(); ?>
II.4.4. Bin hm
Bn c th s dng cc bin hm (tc l bn c th gi hm di dng ten_bien() ). Bin hm thng c s dng cho cc hm callback
<?php function foo() { echo "In foo()<br>\n"; } function bar($arg = '') { echo "In bar(); argument was '$arg'.<br>\n"; } // This is a wrapper function around echo function echoit($string) { echo $string; } $func = 'foo'; $func(); // This calls foo() $func = 'bar'; $func('test'); // This calls bar()
?>
$a = new AClass("a"); $b =& new AClass("b"); $a->setName("quang1"); $global_ref[0]->echoName(); $b->setName("quang2"); $global_ref[1]->echoName(); ?>
<?php class AClass { var $m_flag; }; class BClass extends AClass { function turnOn() { $this->m_flag = true; } };
$a = new AClass(); $b = new BClass(); $a->m_flag = true; $b->turnOn(); $c = new BClass(); $c->turnOn();
var_dump($b==$c); var_dump($a==$b); ?>
}; $a = $b = new AClass(); $a->addFlag("quang", 1); $a->addFlag("quang2", 2); $b->addFlag("quang", 1); $b->addFlag("quang2", 2); var_dump($a==$b); $b->removeFlag("quang"); var_dump($a==$b); ?>
So snh i tng trong PHP5 c mt s thay i so vi PHP4 i vi php so snh ==, hai i tng bng nhau nu c chung cc thuc tnh v cng thuc 1 lp i vi php so snh ===, hai i tng c gi l bng nhau nu chng cng tham chiu n 1 phin bn ca 1 lp
Tham chiu cho php bn s dng 1 bin vi nhiu tn khc nhau i vi i tng, nn s dng php gn tham chiu khi dng ton t new trnh php gn to ra thm 1 phin bn ca i tng thay i gi tr ca tham s truyn vo trong hm, bn c th s dng tham chiu <?php $a = &$b; $b = 100; var_dump($a); class AClass {}; $c = new AClass(); $d =& new AClass();
Tham chiu gn ging con tr nhng bn cht khng phi l con tr Trong trng hp ti v d di y, $var trong hm foo u tin c tham chiu n bin $var (global). Tuy nhin sau $var li c tham chiu in bin $quang (global) <?php function foo(&$var) { $var =& $GLOBALS["quang"]; var_dump($var); } $quang = "Nguyen Phu Quang"; $var = 100; foo($var); var_dump($var); ?>
Bn c th truyn cc dng tham chiu sau: Bin foo($a) Lnh new foo(new AClass()); Tham chiu tr v t hm
<?php function foo(&$num) { $num++; } function &bar() { global $a; return $a; } $a=10; foo($a); var_dump($a); foo(bar()); var_dump($a); foo($a = 5); var_dump($a); foo(5); ?>
Hm c th tr v tham chiu, khi bn t ton t tham chiu ng trc tn hm Nu hm tr v tham chiu, nhn c tham chiu bn phi dng ton t gn vi tham chiu n hm (xem v d)
<?php function &bar() { global $a; return $a; }
$a = 10; $c = bar(); $c++; var_dump($a); var_dump($c); $b =& bar(); $b++; var_dump($a); var_dump($b); ?>
Bn c th s dng lnh unset() loi b mt bin khi b nh Nu unset c s dng vi 1 bin tham chiu, PHP s kim tra xem cn bin no cng tham chiu n vng nh hay khng ri mi loi b bin khi b nh <?php $a = &$b; $b = 100; unset($a); var_dump($a); var_dump($b); unset($b); var_dump($a); var_dump($b); ?>
Cc bin global l cc bin c khai bo mc ngoi cng ca PHP c s dng chung cho mi module Cc bin SuperGlobal l cc bin (mng) c PHP to ra lu cc thng tin cn thit
Array Description Contains keys and values set as browser cookies Contains keys and values set by the script's shell context Contains information about uploaded files Contains keys and values submitted to the script using the HTTP get method Contains keys and values submitted to the script using the HTTP post method A combined array containing values from the $_GET, $_POST, and $_COOKIES superglobal arrays Variables made available by the server Contains all global variables associated with the current script
$_SERVER['REQUEST_URL']
$_SERVER['HTTP_REFERER']
The current script. Suitable for use in links and form element action arguments. The name and version of the client. The IP address of the client. Whether the request was GET or POST. For GET requests, the encoded data sent appended to the URL. The full address of the request, including query string. The address of the page from which the request was made.
/phpbook/source/listing10.1.php
POST
name=matt&address=unknown /phpbook/source/listing10.1.php? name=matt http://p24.corrosive
Nhng cch ly thng tin t form nu trn cho php chng ta lm vic tt vi cc control n (c 1 gi tr) i vi cc control c nhiu gi tr nh select hay checkbox, ny sinh vn l lm sao nhn c tt c cc control c la chn gii quyt vn ny, t tn cc control vi kt thc l du ngoc vung [], khi d liu truyn t form n server s l mng
i vi cc trang PHP nh, bn thng mun kt hp form gi thng tin vi cc on script PHP x l thng tin. iu ny c th d dng thc hin bng cch cc kt hp cc cu trc iu khin r nhnh vi cc on m HTML. t on m HTML vo trong cu trc r nhnh, s dng kt hp cc khi lnh PHP (xem v d)
III.6. Redirect
R rng l vic hardcode HTML cng vi s dng nhiu khi PHP xen ln HTML l khng tt. Mt cch n gin v hiu qu hn l s dng Redirect dn hng ngi dng n cc trang thch hp (v d: Trang ng nhp nu ngi dng cha ng nhp, trang chc mng nu ngi dng ng nhp thnh cng) lm c vic ny, trc ht ta tm hiu c ch lm vic gia PHP script v client. u tin, giao tip vi client, PHP t ng gi cc thng tin header cho client. Tuy nhin, bn vn c th t gi header. dn hng client n trang khc, bn ch cn n gin i header bng hm header(). s dng hm header() bn phi m bo rng cho c d liu no c gi cho client (s dng hm header_sent() kim tra)
Mng $_FILE
Element Contains Name of uploaded file Path to temporary file Size (in bytes) of uploaded file An error code corresponding to a PHP constant Example
test.gif /tmp/phprDfZvN
6835
UPLOAD_ERR_FORM _SIZE
$_FILES['fupload']['type']
image/gif
Constant Name
UPLOAD_ERR_OK UPLOAD_ERR_INI_SIZE UPLOAD_ERR_FORM_SIZE
Valu e
0 1 2
File size exceeds limit set in hidden element named MAX_FILE_SIZE File only partially uploaded File was not uploaded
UPLOAD_ERR_PARTIAL UPLOAD_ERR_NO_FILE
3 4
<?php if ($_REQUEST["submit"]=="upload!") { echo $_FILES["fupload"]["error"], "\n"; echo $_FILES["fupload"]["size"], "\n"; echo $_FILES["fupload"]["name"], "\n"; echo $_FILES["fupload"]["tmp_name"], "\n"; if ($_FILES["fupload"]["error"]==0) { $source = $_FILES["fupload"]["tmp_name"]; $dest = $_FILES["fupload"]["name"]; move_uploaded_file($source, $dest); } } ?> <form enctype="multipart/form-data" method="post"> <p> <input type="hidden" name="MAX_FILE_SIZE" value="102400" /> <input type="file" name="fupload" /><br/> <input type="submit" value="upload!" name="submit" /> </p> </form>
Lnh include() cho php bn phi hp gia cc file trong mt PHP project, ko ging nh c php #include ca ngn ng C, lnh ny khng chn m lnh vo file m thc thi file php ging nh c php gi hm include() s dng chia s cc hm dng chung, cc on m chung trong mt project c nhiu file Nu khng tm thy file, include() thng bo warning nhng khng dng chng trnh PHP cung cp 1 lnh tng t include() l require(), lnh ny c s khc bit l s dng ngay chng trnh khi khng tm thy file
<!--File1.php-> <?php echo "This is from file 1\n"; ?> <!--File2.php -> <?php echo "This is from file 2\n"; include("file1.php"); include("file3.php"); echo "This is from file 2\n"; ?>
V include() thc hin li gi n file php, do bn c th tr v gi tr t file PHP c include <!--File11.php--> <?php return 4 + 4; ?> <!--File12.php--> <?php echo "This is from file 12\n"; $retVal = include("file11.php"); echo "Return value from file 11: \$retVal= $retVal\n"; echo "This is from file 12\n"; ?>
Bn c th t lnh include bn trong 1 cu trc iu kin hoc cu trc lp, khi ty theo iu kin ca cu trc m include() c c thc hin hay khng, 1 hay nhiu ln <!--File22.php--> <?php if ($j==null) $j=10; else $j++; return $i+$j; ?> <!--File21.php--> <?php for ($i=0; $i<10; $i++) { echo include("File22.php"), "\n"; } ?>
include_once() ging nh include(), tuy nhin c im khc bit l ch include 1 ln, ln sau nu gp li file ny th ko include na include_once() s dng cho cc hm th vin dng chung trnh trng hp khi nhiu file cng include n 1 file, sau cc file ny li include ln nhau (so snh vi #ifdefine trong file header ca ngn ng C) include_once() phn bit ch hoa, ch thng <?php include_once("a.php"); // this will include a.php include_once("A.php"); // this will include a.php again on Windows! ?>
Trong qu trnh lm vic, bn hn c nhiu hm c dng chung gia nhiu file trong 1 project, gia nhiu project. s dng cc hm ny, bn c th p dng cc cch sau:
include file theo ng dn tuyt i: Cch ny d v khi ci t trn my khc s khng tm thy file c include include file theo ng dn tng i: Cch ny tt hn, nhng mi khi i v tr ca file c include th phi sa li ti tt c cc file thc hin li gi include Cch tt nht l s dng include_path (thit lp trong file PHP.INI) i vi nhng file th vin dng chung c s dng nhiu (ging nh i vi ngn ng C)
<?php var_dump(get_include_path()); set_include_path('/inc'); // Works as of PHP 4.3.0 var_dump(get_include_path()); restore_include_path(); var_dump(get_include_path()); ?>
<?php var_dump(ini_get("include_path")); ini_set("include_path", "/inc"); // Works in all PHP versions var_dump(ini_get("include_path")); ini_restore("include_path"); var_dump(ini_get("include_path")); ?>
fopen($filename, $mode); fwrite($handle, $string); fread($handle, $length); fgets($handle); sprintf($format); fscanf($handle, $format);
<?php $var1=10; $var2=100; $var3=100.3434; $var4="Test string"; $f=fopen("test.txt", "wt"); fwrite($f, sprintf("%d %10.3f %10.3lf\n\r", $var1, $var2, $var3)); fwrite($f, sprintf("%s", $var4)); fclose($f); $f=fopen("test.txt", "rt"); if (list($v1, $v2, $v3, $v4) = fscanf($f, "%d %f %lf\n\r%s")) { var_dump($v1); var_dump($v2); var_dump($v3); var_dump($v4); } $v4 = fgets($f); var_dump($v4); fclose($f); ?>
<?php class AClass { }; $ob1 =& new AClass(); $ob1->a = 10; $ob1->b = 100.023; $ob1->c = "Test String"; var_dump($ob1); $f = fopen("test.txt", "wb"); fwrite($f, serialize($ob1)); fclose($f); $f = fopen("test.txt", "rb"); $ob2 = unserialize(fgets($f)); fclose($f); var_dump($ob2); ?>
IV.5. Lm vic vi th mc
mkdir(), rmdir(), opendir(), readdir(), closedir() <?php $dir=opendir("c:\\windows"); while ($file=readdir($dir)) { echo "$file\n"; } closedir($dir); ?>
u im: Tc cao do c thit k cho tng CSDL c th. Tn dng c u im ca tng loi CSDL Nhc im: Khng c tnh kh chuyn gia cc CSDL
u im: C th s dng trn nhiu CSDL khc nhau Nhc im: Chm hn phng php trn, khng tn dng c u im ca tng CSDL.
Ci t th vin PEAR
Yu cu: PHP phin bn 5.0 Ci t PHP Chy go-pear.bat Theo cc hng dn trong chng trnh (cc tham s ch cn t mc nh)
Nu khng ci t PEAR, m copy t my khc, phi thm vo C:/Windows/PHP.INI 2 dng nh di Cu hnh Zend Studio lm vic vi PEAR DB
Thm vo file $Zend_dir/bin/php5/php.ini 2 dng include_path=".;C:/php/pear" extension_dir="c:/php/ext" Copy file libMySQL.dll vo $Windows/$System (nu bn s dng IIS)
Cc bc ci t kiu m n lin
Ci IIS, ci Mysql 5.0, ci PHP Copy $\Mysql\bin\libMysql.dll n c:\windows\system32 Copy PHP.rar ln th mc c:/PHP Sa ni dung c:\windows\system32\PHP.INI, thm vo cc dng sau ( cui file)
include_path=".;C:/php/pear" extension_dir=" c:/php/ext" extension=php_mysql.dll
Sau , c th chy c trn local host (trn Zend th phi config thm, tt nht l ng config)
V.2. PEAR DB
<?php require("DB.php"); $dsn = "mysql://root:root@localhost/dhxd"; $db = DB::connect($dsn); if (DB::isError($db)) die($db->getMessage()); $table = $db->query("SELECT * FROM SV"); if (DB::isError($table)) die($table->getMessage()); echo "<table border='1'>"; while ($row = $table->fetchRow()) { echo "<tr> <td>$row[0]</td> <td>$row[1]</td> <td>$row[2]</td> <td>$row[3]</td> </tr>"; } echo "</table>";
?>
Database
oci8
Odbc Sybase Ifx Fbsql
Oracle 7/8/8i
ODBC SyBase Informix FrontBase
V.2.2. Kt ni vi c s d liu
options c th l 1 gi tr Boolean hoc 1 $db = DB::connect($dsn, array('debug' => 1, 'optimize' => 'portability'));
mng
Cc phng thc ca DB tr v DB_ERROR nu c li trong qu trnh thc hin Bn c th kim tra 1 kt qu tr v c phi l li khng bng hm DB::isError(); Nu DB::isError() tr v true, kt qu tr v ca bn l li, c th xem thng bo li bng phng thc $tenbien>getMessage() $db = DB::connect($datasource); if (DB::isError($db)) { die($db->getMessage( )); }
thc thi query, s dng phng thc query() ca Database Object (i tng tr v khi bn kt ni thnh cng vi CSDL bng hm DB::connect() ); $db = DB::connect($datasource); $result = $db->query(sql); Cng tng t nh DB::connect(), bn c th kim tra li bng DB::isError() if (DB::iserror($result)) { die($result->getMessage()); }
V.2.5. Ly kt qu t query
$row = $result->fetchRow([ mode ]); Hm fetchRow() tr v mng cc gi tr trn dng hoc DB_ERROR (nu c li) <?php $db = DB::connect($datasource); $result = $db->query(sql); while ($row = $result->fetchRow( )) { if (DB::isError($row)) { die($row->getMessage( )); } // do something with the row } ?>
DB_FETCHMODE_ORDERED: Cc ct c lit k trn $row theo th t 0,1,2... DB_FETCHMODE_ASSOC : Cc ct c lit k vi kha l tn ca cc ct DB_FETCHMODE_OBJECT: Cc ct c lit k thnh cc trng ca i tng
<?php require("DB.php"); $db = DB::connect("mysql://root:root@localhost/d hxd"); $table = $db->query("select * from sv"); $row = $table->fetchRow(); unset($row); $table->free(); $db->disconnect(); ?>
xy dng cc query, nu dng php ni xu k t rt d gy nhm ln do khng nhn thy tng th ca cu lnh SQL (nht l vi cc trng hp c s dng du nhy) Trong trng hp ny, PHP cung cp 1 cng c hot ng cho php truyn tham s trong cu lnh SQL ging nh lnh printf, trong s dng cc k hiu
?: Cho s hoc string (du nhy s c b sung khi cn thit) |: Cho s hoc string (khng s dng du nhy) &: Tn file (dng cho cc trng BLOB)
<?php require("DB.php"); $db = DB::connect("mysql://root:root@localhost/dhxd"); $row = array("Nguyen Van", "A"); $db->query("INSERT INTO sv (hodem, ten) VALUES(?,?)", $row); ?>
V.3.2. Prepare/Execute
Khi bn thc hin nhiu cu lnh ging nhau, cch tt nht l dch cu lnh SQL trc khi thc hin bng phng thc prepare() Sau khi dch SQL, bn c th thc hin cu lnh SQL bng cch dng 2 lnh sau:
$response = $db->execute(compiled, values); (values: mng 1 chiu cc gi tr) $responses = $db->executeMultiple(compiled, values); (values: mng 2 chiu cc dng, mi dng l 1 mng 1 chiu cc gi tr)
<?php require("DB.php"); $db = DB::connect("mysql://root:root@localhost/dhxd"); $complied = $db->prepare("INSERT INTO sv (hodem, ten) VALUES(?,?)"); $rows=array( array("Nguyen Van", "A"), array("Nguyen Van", "B"), array("Nguyen Van", "C"), array("Nguyen Van", "D") ); foreach ($rows as $row) { $db->execute($complied, $row); } $db->executeMultiple($complied, $rows); ?>
V.3.3. Cc hm tin ch
Ngoi
cc hm chung, PEAR DB cn cung cp cc hm cho php thc hin nhanh 1 s chc nng hay c s dng: getOne(), getRow(), getCol(), getAssoc(), getAll() <?php require("DB.php"); $db = DB::connect("mysql://root:root@localhost/dhxd"); $result = $db->getRow("SELECT * FROM sv"); var_dump($result); $result = $db->getOne("SELECT count(*) FROM sv"); var_dump($result); $result = $db->getCol("SELECT * FROM sv", "ten"); var_dump($result); $result = $db->getAssoc("SELECT * FROM sv"); var_dump($result); $result = $db->getAll("SELECT * FROM sv"); var_dump($result); ?>
V.3.5. Metadata
Hm getListOf() s dng ly thng tin v users, databases, tables, views, functions (ph thuc vo s h tr ca CSDL m bn ang s dng) <?php require_once("DB.php"); $db = DB::connect("mysql://root:root@localhost/dhxd"); $result = $db->getListOf("users"); var_dump($result); $result = $db->getListOf("databases"); var_dump($result); $result = $db->getListOf("tables"); var_dump($result); ?>
V.3.6. Transaction
Nhiu c s d liu h tr Transaction safe, s dng transaction safe trong PHP, bn s dng cc lnh commit(), rollback() c th rollback(), bn phi thit lp autocommit l false
<?php require_once("DB.php"); $db = DB::connect("mysql://root:root@localhost/dhxd"); $db->autocommit = false; $result = $db->query("DELETE FROM sv;"); $db->rollback(); $db->autocommit = true; ?>
Trang Web c giao din d thay i l 1 tiu ch rt quan trng Nu kt hp m HTML v PHP khng tt th rt kh cho ngi thit k giao din v ngi lp trnh lm vic vi nhau kh nng thay i giao din kh khn Mt phng php hiu qu l s dng cc file template (.HTML c thit k t cc chng trnh: DW, FrontPage...). Cc file template ny thng khng cha m PHP m ch c cc thng tin di dng quy c (thng l cc tn gi, gi tr c t theo 1 quy c nht nh, cc gi tr ny s c thay th khi chy chng trnh bng PHP)
Thng th cc hm ghi thng tin ra browser. Tuy nhin c nhiu trng hp chng ta khng mun nh vy. Bn c th s dng vng m ra (output buffer) cc lnh ghi thng tin ghi d liu ln Cc hm vi output buffer: ob_start(), ob_get_length(), ob_get_contents(), ob_flush(), ob_end_flush(); ob_end_clean() <?php ob_start(); phpinfo(); $phpinfo = ob_get_contents(); ob_end_clean();
if (strpos($phpinfo, "module_pdf") === FALSE) { echo "You do not have PDF support in your PHP, sorry."; } else { echo "Congratulations, you have PDF support!"; } ?>
VI.4. Qun l li
VI.4.1. Thng bo li VI.4.2. Giu li VI.4.3. Pht sinh li VI.4.4. Hm x l li VI.4.5. Log li
VI.4.1. Thng bo li
Thng thng, khi c li, thng bo li c in ra output C 3 mc thng bo: notices, warnings, errors Mc nh ca PHP l cc thng bo warning, error s c in ra browser, bn c th thay i trong PHP.INI hoc trong thi gian chy bng hm error_reporting() (cc tham s E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR)
E_PARSE
E_NOTICE E_CORE_ERROR E_CORE_WARNING E_COMPILE_ERROR E_COMPILE_WARNING E_USER_ERROR E_USER_WARNING E_USER_NOTICE
E_ALL
VI.4.2. Giu li
S dng ton t @ ngn khng cho output li ra browser Thit lp track_errors trong php.ini bt c cc thng bo li qua bin $php_errormsg ngn khng cho tt c cc thng bo li trn browser, s dng hm error_reporting(0) <?php ini_set("track_errors", "1"); $value = 2/0; $value = @(2/0); echo "$php_errormsg"; ini_restore("track_errors"); ?> <?php error_reporting(0); ini_set("track_errors", "1"); $value = 2/0; echo "$php_errormsg"; ini_restore("track_errors"); ?>
Bn c th lm pht sinh li ngi dng bng hm trigger_error trigger_error(message [, type]); type: E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE (default)
<?php function divider($a, $b) { if($b == 0) { trigger_error('$b cannot be 0', _USER_ERROR); } } ?> return($a / $b);
VI.4.4. Hm x l li
Giu tt c cc li khng phi l mt phng n hay, qun l li tt hn, bn nn dng hm x l li (error handler) Error handler c thit lp bng hm set_error_handler(), khi phc li bng hm restore_error_handler()
<?php function my_handler($error, $errorstring, $filename, $line, $symbol) { echo "$error|$errorstring|$filename|$line\n"; } set_error_handler('my_handler'); echo 4/0; $f = file("linhtinh"); ?>
VI.4.5. Log li
VI.5. Ti u ha
VII. Hnh nh
VII.1. Yu cu phn mm VII.2. To v v nh VII.3. V Text VII.4. Co dn nh
VII.1. Yu cu phn mm
Vi PHP bn c th s dng cc hm graphic v ra cc hnh nh v lu tr di dng file (GIF, PNG, JPG) thc hin c chc nng ny, bn cn phi ci t b th vin GD (http://www.boutell.com/gd/ ) bit th vin GD c ci t hay cha, c th s dng hm phpinfo() hoc hm gd_info() i vi b PHP full (v5.0) c y th vin PEAR i km, chy GD bn ch vic thit lp trong file php.ini: extension=php_gd2.dll
VII.2. To v v nh
<!-- file: caro.php --> <?php $im = imagecreate(30, 30); $red = imagecolorallocate($im, 0xff, 0x00, 0x00); $blue = imagecolorallocate($im, 0x00,0x00,0xff); $black = imagecolorallocate($im, 0x00, 0x00, 0x00); imagefilledrectangle($im, 0, 0, 29, 29, $black); imagefilledrectangle($im, 0,0,15,15,$red); imagefilledrectangle($im, 15,15,29,29,$blue); imagejpeg($im); ?> <!-- file: 1.html --> <html> Day la caro <img src="caro.php"/> </html> <?php $im = imagecreate(30, 30); $red = imagecolorallocate($im, 0xff, 0x00, 0x00); $blue = imagecolorallocate($im, 0x00,0x00,0xff); $black = imagecolorallocate($im, 0x00, 0x00, 0x00); imagefilledrectangle($im, 0, 0, 29, 29, $black); imagefilledrectangle($im, 0,0,15,15,$red); imagefilledrectangle($im, 15,15,29,29,$blue); imagejpeg($im, "c:/test.jpg", 100); ?> <html> Day cung la caro: <img src = "c:/test.jpg"/> </html>
VII.2. To v v nh (2)
Cc hm thng s dng
resource imagecreate ( int x_size, int y_size ): To nh vi kch thc x_size * y_size, nh ko phi truecolor imagecolorallocate ( resource image, int red, int green, int blue ): S dng nh ngha 1 mu s xut hin trong nh. i vi nh s dng palette, ln gi u tin s cho mu l mu nn ca nh resource imagecreatetruecolor ( int x_size, int y_size ): To nh truecolor bool imagejpeg ( resource image [, string filename [, int quality]] ) bool imagepng ( resource image [, string filename] ) bool imagegif ( resource image [, string filename] )
VII.2. To v v nh (3)
ImageSetPixel(image, x, y, color); ImageLine(image, start_x, start_ y, end_x, end_ y, color); ImageDashedLine(image, start_x, start_ y, end_x, end_ y, color); ImageRectangle(image, tlx, tly, brx, bry, color); ImageFilledRectangle(image, tlx, tly, brx, bry, color); ImagePolygon(image, points, number, color); ImageFilledPolygon(image, points, number, color); ImageArc(image, center_x, center_ y, width, height, start, end, color); ImageFill(image, x, y, color); ImageFillToBorder(image, x, y, border_color, color);
VII.3. V Text
<?php $im = imagecreate(100,100); $white = imagecolorallocate($im, 0xff, 0xff, 0xff); $red = imagecolorallocate($im, 0xff, 0x00, 0x00); imagestring($im, 1, 0, 0, "HUCE", $red); imagestring($im, 2, 0, 10, "HUCE", $red); imagestring($im, 3, 0, 20, "HUCE", $red); imagestring($im, 4, 0, 30, "HUCE", $red); imagestring($im, 5, 0, 45, "HUCE", $red); imagestringup($im, 5, 50, 99, "University", $red); imagegif($im); ?>
VII.4. Co dn nh
<?php $im = imagecreate(100,100); $white = imagecolorallocate($im, 0xff, 0xff, 0xff); $red = imagecolorallocate($im, 0xff, 0x00, 0x00); $blue = imagecolorallocate($im, 0x00, 0x00, 0xff); imagettftext($im, 8, 30, 10, 100, $red, "Times", "HUCE - 46pm1"); imagettftext($im, 10, -30, 10, 10, $blue, "Arialni", "HUCE - 46pm1"); $im2 = imagecreate(200, 200); //imagecopyresized($im2, $im, 0, 0, 0, 0, 200, 200, 100, 100); imagecopyresampled($im2, $im, 0, 0, 0, 0, 200, 200, 100, 100); imagegif($im2); ?>
VII.5. Mu sc
VII.5.1. True color & color index VII.5.3. Knh alpha
nh ca bn c to bi cc hm imagecreate() to nh s dng colorindex trn palette v imagecreatetruecolor () to nh truecolor (24bit/pixel) T GD2.0 tr ln, ta c th lm vic vi knh alpha (xem phn sau) ly mu ca im nh
Vi nh truecolor, cu trc mu gm: 7bit alpha, 8bit Red, 8bit Green, 8bit Blue (t tri qua phi). C th s dng cng thc sau
$a $r $g $b
= = = =
Knh alpha trong GD ch gm 7bit (gi tr t 0 n 127) s dng knh alpha s dng cc hm
ImageColorResolveAlpha() ImageAlphaBlending()
<?php $im = ImageCreateTrueColor(150,150); $white = ImageColorAllocate($im,255,255,255); ImageAlphaBlending($im, true); ImageFilledRectangle($im,0,0,150,150,$white); $red = ImageColorResolveAlpha($im,255,50,0,63); ImageFilledEllipse($im,75,75,80,50,$red); $gray = ImageColorResolveAlpha($im,70,70,70,63); ImageAlphaBlending($im, true); ImageFilledRectangle($im,60,60,120,120,$gray); header('Content-Type: image/png'); ImagePNG($im); ?>
IX. XML
IX.1. To vn bn XML IX.2. c XML
IX.1. To vn bn XML
header('Content-Type: text/xml');
IX.2. c XML
<?php function start_element($inParser, $inName, &$inAttributes) { var_dump($inName); var_dump($inAttributes); } function end_element($inParser, $inName) { var_dump($inName); } $xml = xml_parser_create(); xml_set_element_handler($xml, "start_element", "end_element"); xml_parse($xml, "<xml><row name='row1' atr='attribute1'/></xml>"); ?>
VIII. PDF
VIII.1. Document & Page VIII.2. Text VIII.3. Images & Graphics VIII.4. Nagivations VIII.5. Cc chc nng khc