Presentation is loading. Please wait.

Presentation is loading. Please wait.

PHP/MySQL Tutorial Nguyễn Quang Hùng Web site:

Similar presentations


Presentation on theme: "PHP/MySQL Tutorial Nguyễn Quang Hùng Web site:"— Presentation transcript:

1 PHP/MySQL Tutorial Nguyễn Quang Hùng Web site:

2 Nguyễn Quang Hùng – Mục tiêu Nắm bắt công nghệ lập trình trang web động bằng PHP. Tìm hiểu về cách truy vấn CSDL MySQL từ PHP. Viết một ứng dụng Tra cứu danh bạ điện thoại bằng JSP.

3 Nguyễn Quang Hùng – Lập trình web phía server Lập trình Web với CGI (tự học) Lập trình Web với ASP/ASP.NET (tự học) Lập trình Web với Servlet (tự học) Lập trình Web với JSP (chương 7) Lập trình Web với PHP (hôm nay)

4 Nguyễn Quang Hùng – Introduction PHP (Hypertext Preprocessor) - Open source, server-side, scripting language. - Supports databases such as MySQL and Oracle. - MySQL (Structured Query Language) - Open source, speedy, scalable, reliable database technology. -

5 Nguyễn Quang Hùng – Tutorial Overview Database (MySQL) DB creation Add/delete tables Add/delete/update records View/query records Web (PHP) User front-end Add & query code Delete & update code

6 Nguyễn Quang Hùng – MySQL & TCD (1) ‘PuTTY’ into wilde.cs.tcd.ie on port 22 w/ SSHPuTTY - Authenticate with your TCD username and password (2) ssh macneil.cs.tcd.ie (password as above) (3) Login into your MySQL account ‘mysql –uUSERNAME –p’ Enter your MySQL username and password (4) Use MySQL syntax to create and view table(s), records, etc.

7 Nguyễn Quang Hùng – Basic MySQL Syntax SHOW DATABASES; USE database_name; SHOW TABLES; DROP TABLE table_name;

8 Nguyễn Quang Hùng – Create MySQL Table CREATE TABLE user ( name varchar(9) NOT NULL, id int(6) NOT NULL, PRIMARY KEY (id), UNIQUE (id) );

9 Nguyễn Quang Hùng – Add/Delete/Update Table INSERT INTO user VALUES (‘bond’, ‘007’); DELETE FROM user WHERE id=‘007’; UPDATE user SET name=‘BOND’ WHERE id=‘007’;

10 Nguyễn Quang Hùng – Query Database SELECT * FROM user; SELECT * FROM user WHERE name=‘BOND’; SELECT DISTINCT name FROM user; SELECT name, id FROM user ORDER BY name;

11 Nguyễn Quang Hùng – MySQL Administrator GUI tool

12 Nguyễn Quang Hùng – PHP User Front-End Script is executed server side and presented to user via a browser. PHP code is rendered as plain HTML.

13 Nguyễn Quang Hùng – PHP Configuration File Use a securely positioned ‘config’ file to store variables. Other PHP pages can link to it and use the variables as their own.

14 Nguyễn Quang Hùng – PHP Add to DB Code 1 Title Authors …

15 Nguyễn Quang Hùng – PHP Add to DB Code 2

16 Nguyễn Quang Hùng – PHP Query Code include("conf.php"); $connection = mysql_connect($host, $user, $pass) or die (); mysql_select_db($db) or die ("Unable to select database!"); $query = "SELECT * FROM papers"; $result = mysql_query($query) or die ("Error in query”); ?> 0) { // iterate through resultset & print title with links to edit and delete scripts while($row = mysql_fetch_object($result)) ?> id; ?>">edit/view | id; ?>">delete title; ?> - authors; ?> url; ?>" target="_blank"> pdf

17 Nguyễn Quang Hùng – PHP Delete Code include("conf.php"); // form not yet submitted, display initial form with values pre-filled $id=$_GET['id']; { // open database connection $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); // select database mysql_select_db($db) or die ("Unable to select database!"); // generate and execute query $query = "DELETE FROM papers WHERE id = '$id'"; $result = mysql_query($query) or die ("Error in query: $query. ". mysql_error()); // close database connection mysql_close($connection); // print result echo " Deletion successful. Go back to the main page | home "; }

18 Nguyễn Quang Hùng – PHP Update Code 1 $id=$_GET['id']; if (!$submit) { $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); mysql_select_db($db) or die ("Unable to select database!"); $query = "SELECT title, authors, description, comment, super, bibtex, url, genre FROM papers WHERE id = '$id'"; $result = mysql_query($query) or die ("Error in query: $query. ". mysql_error()) if (mysql_num_rows($result) > 0) { $row = mysql_fetch_object($result); // print form with values pre-filled ?> "> Title title; ?> Authors authors; ?> …

19 Nguyễn Quang Hùng – PHP Update Code 2 include("conf.php"); // form submitted so start processing it $title = $_POST["title"]; $authors = $_POST["authors"]; $id = $_POST["id"]; // set up error list array $errorList = array(); $count = 0; // validate text input fields if (!$title) { $errorList[$count] = "Invalid entry: Title"; $count++; } if (!$contact) { $contact = $def_contact; } // check for errors, if none found... if (sizeof($errorList) == 0) { $connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); mysql_select_db($db) or die ("Unable to select database!"); $query = "UPDATE papers SET title = '$title', authors = '$authors', description = '$description', comment = '$comment', super = '$super', bibtex = '$bibtex', url = '$url', genre = '$genre' WHERE id = '$id'"; $result = mysql_query($query) or die ("Error in query: $query. ". mysql_error()); // print result echo " Update successful. Go back to the main page | home "; // close database connection mysql_close($connection); } else{} ?>

20 Nguyễn Quang Hùng – Tài liệu tham khảo

21 Nguyễn Quang Hùng – Brief History of PHP PHP (PHP: Hypertext Preprocessor) was created by Rasmus Lerdorf in It was initially developed for HTTP usage logging and server-side form generation in Unix. PHP 2 (1995) transformed the language into a Server-side embedded scripting language. Added database support, file uploads, variables, arrays, recursive functions, conditionals, iteration, regular expressions, etc. PHP 3 (1998) added support for ODBC data sources, multiple platform support, protocols (SNMP,IMAP), and new parser written by Zeev Suraski and Andi Gutmans. PHP 4 (2000) became an independent component of the web server for added efficiency. The parser was renamed the Zend Engine. Many security features were added. PHP 5 (2004) adds Zend Engine II with object oriented programming, robust XML support using the libxml2 library, SOAP extension for interoperability with Web Services, SQLite has been bundled with PHP

22 Nguyễn Quang Hùng – Brief History of PHP As of August 2004, PHP is used on 16,946,328 Domains, 1,348,793 IP Addresses This is roughly 32% of all domains on the web.

23 Nguyễn Quang Hùng – Why is PHP used? 1.Easy to Use Code is embedded into HTML. The PHP code is enclosed in special start and end tags that allow you to jump into and out of "PHP mode". Example

24 Nguyễn Quang Hùng – Why is PHP used? 2.Cross Platform Runs on almost any Web server on several operating systems. One of the strongest features is the wide range of supported databases Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise Server Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux), Mac OSX, Windows NT/98/2000/XP/2003 Supported Databases: Adabas D, dBase,Empress, FilePro (read- only), Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL, Direct MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos, PostgreSQL, SQLite, Solid, Sybase, Velocis,Unix dbm

25 Nguyễn Quang Hùng – Why is PHP used? 3.Cost Benefits PHP is free. Open source code means that the entire PHP community will contribute towards bug fixes. There are several add-on technologies (libraries) for PHP that are also free. PHP SoftwareFree PlatformFree (Linux) Development ToolsFree PHP CoderPHP Coder, jEditjEdit

26 Nguyễn Quang Hùng – Getting Started 1. How to escape from HTML and enter PHP mode PHP parses a file by looking for one of the special tags that tells it to start interpreting the text as PHP code. The parser then executes all of the code it finds until it runs into a PHP closing tag. Starting tagEnding tagNotes Preferred method as it allows the use of PHP with XHTML Not recommended. Easier to type, but has to be enabled and may conflict with XML ?>Always available, best if used when FrontPage is the HTML editor <%>Not recommended. ASP tags support was added in PHP CODE HTML

27 Nguyễn Quang Hùng – Getting Started 2. Simple HTML Page with PHP The following is a basic example to output text using PHP. My First PHP Page Copy the code onto your web server and save it as “test.php”. You should see “Hello World!” displayed. Notice that the semicolon is used at the end of each line of PHP code to signify a line break. Like HTML, PHP ignores whitespace between lines of code. (An HTML equivalent is )

28 Nguyễn Quang Hùng – Getting Started 3. Using conditional statements Conditional statements are very useful for displaying specific content to the user. The following example shows how to display content according to the day of the week.

29 Nguyễn Quang Hùng – Getting Started 3. Using conditional statements The if statement checks the value of $today_dayofweek (which is the numerical day of the week, 0=Sunday… 6=Saturday) If it is equal to 4 (the numeric representation of Thurs.) it will display everything within the first { } bracket after the “if()”. If it is not equal to 4, it will display everything in the second { } bracket after the “else”.

30 Nguyễn Quang Hùng – Getting Started 3. Using conditional statements If we run the script on a Thursday, we should see: “Today is Thursday”. On days other than Thursday, we will see: “Today is not Thursday.”

31 Nguyễn Quang Hùng – Examples PHP is a great way to implement templates on your website. How to implement a simple page counter

32 Nguyễn Quang Hùng – Examples Step 1: Universal header and footer in a single file Create a file called header.php. This file will have all of the header HTML code. You can use FrontPage/Dreamweaver to create the header, but remember to remove the closing and tags. UCR Webmaster Support Group Page Title

33 Nguyễn Quang Hùng – Examples Step 2: Universal header and footer in a single file Next, create a file called footer.php. This file will have all of the footer HTML code. UC Riverside Department

34 Nguyễn Quang Hùng – Examples Step 3: Universal header and footer in a single file This is the basic template that you will use on all of the pages. Make sure you name the files with a.php extension so that the server will process the PHP code. In this example, we assume the header and footer files are located in the same directory. Insert content here!

35 Nguyễn Quang Hùng – Examples Benefits: - Any changes to header or footer only require editing of a single file. This reduces the amount of work necessary for site maintenance and redesign. - Helps separate the content and design for easier maintenance Page 1 Content Page 5 Content Page 3 Content Page 2 Content Page 4 Content Header Footer

36 Nguyễn Quang Hùng – Examples Step 1: Simple Page Counter Download the counter file webcounter.txt onto your machinewebcounter.txt Upload the webcounter.txt file onto your web server (via FTP, WinSCP, etc) Change the file permissions of the webcounter.txt file to 777 to allow the counter file to be updated.

37 Nguyễn Quang Hùng – Examples Step 2: Simple Page Counter Copy this code into a page where you want a counter.

38 Nguyễn Quang Hùng – Examples Step 3: Simple Page Counter Next, output the counter value using PHP. Copy this line after the main block of code. This page has been viewed times. That’s it! The result should look something similar to:

39 Nguyễn Quang Hùng – Examples Step 3: Simple Page Counter You can change the text around the tags to your liking. visitors. This example shows 1.How to escape from HTML and enter PHP mode 2.How to output variables onto the screen using PHP

40 Nguyễn Quang Hùng – Examples 2. How to output variables using PHP Echo is the common method in outputting data. Since it is a language construct, echo doesn’t require parenthesis like print(). Output Text Usage: // prints out Hello World Output the value of a PHP variable: // prints out the number of hits Echo has a shortcut syntax, but it only works with the “short open tag” configuration enabled on the server.

41 Nguyễn Quang Hùng – Examples 3. Other uses with echo() Automatically generate the year on your pages. This will print out ©2004 UC Riverside. © UC Riverside You will need to escape any quotation marks with a backslash.

42 Nguyễn Quang Hùng – Additional Resources PHP Manual PHP Tutorial PHP Coder JEdit PHP's creator offers his thoughts on the PHP phenomenon, what has shaped and motivated the language, and where the PHP movement is heading Hotscripts – A large number of PHP scripts can be found at:

43 Nguyễn Quang Hùng – Additional Information Some of the new functions added in version 5: Arrays: array_combine() - Creates an array by using one array for keys and another for its values array_combine() array_walk_recursive() - Apply a user function recursively to every member of an array array_walk_recursive() Date and Time Related: idate() - Format a local time/date as integer idate() date_sunset() - Time of sunset for a given day and location date_sunset() date_sunrise() - Time of sunrise for a given day and location date_sunrise() time_nanosleep() - Delay for a number of seconds and nano seconds time_nanosleep() Strings: str_split() - Convert a string to an array str_split() strpbrk() - Search a string for any of a set of characters strpbrk() substr_compare() - Binary safe optionally case insensitive comparison of two strings from an offset, up to length characters substr_compare() Other: php_check_syntax() - Check the syntax of the specified file php_check_syntax() php_strip_whitespace() - Return source with stripped comments and whitespace php_strip_whitespace()


Download ppt "PHP/MySQL Tutorial Nguyễn Quang Hùng Web site:"

Similar presentations


Ads by Google