Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Pertemuan 13 PHP-MySQL Last Updated: 15 th May 2010 By M. Arief

Similar presentations


Presentation on theme: "1 Pertemuan 13 PHP-MySQL Last Updated: 15 th May 2010 By M. Arief"— Presentation transcript:

1 1 Pertemuan 13 PHP-MySQL Last Updated: 15 th May 2010 By M. Arief http://arief.ismy.web.id

2 2 Objectives ► To understand what PHP is and how a PHP script works with a Web Browser and a Web Server ► To create and run a simple PHP script To learn how to store and access data in PHP variables ► To understand the advantages of using databases in Web applications ► To learn how to prepare a MySQL database for use with PHP ► To learn how to store, retrieve, and update data in a MySQL database http://arief.ismy.web.id

3 3 References ► http://www.php.net ► http://www.mysql.org ► http://www.apache.org http://arief.ismy.web.id

4 4 PHP History ► PHP originally stood for Personal Home Pages ► PHP is now a recursive acronym that stands for Hypertext Preprocessor ► Rasmus Lerdorf created Personal Homepage Tools/Form Interpreter in 1995. ► In 1997 PHP/FI was rewritten: 50,000 domains were using it. ► In 1998, college students Andi Gutmans and Zeev Suraski rewrote it, released v3 and renamed it PHP: ► Hypertext Preprocessor. Over 1 million domains. ► Late 1998, Zeev and Andi rewrote it again, and called it v4; Developed the Zend Engine which precompiled code. ~20 million domains today. http://arief.ismy.web.id

5 5 PHP History ► Some of PHP’s main competitors are Perl, ASP, JSP and ColdFusion ► PHP has many strengths that include:  High performance  Interface to many different database systems  Build-in libraries for many common web tasks  It is free  Ease of learning and use  Strong object-oriented support  Portability  Availability of source code  Availability of support http://arief.ismy.web.id

6 6 PHP History http://arief.ismy.web.id

7 7 Server Side Scripting ► ► Not a Client Side Scripting (JavaScript, VBScript) ► ► Main scripting languages   PHP (PHP: Hypertext Preprocessor)   JSP (Java Server Pages)   ASP.NET (Active Server Pages)   ColdFusion   Perl http://arief.ismy.web.id

8 8 PHP is C or Java Style ► ► PHP is based on C and Perl. ► ► As a consequence if you know C, Perl, C++ or java (also a C++ clone), or indeed almost any other computer science language you pretty much already know PHP. http://arief.ismy.web.id

9 9 PHP Tag Style ► ► XML Style: ► ► ► ► Short Style: ► ► ► ► Script Style: ► ► PHP Code In Here http://arief.ismy.web.id

10 10 Embedding PHP in HTML Search results for " " http://arief.ismy.web.id

11 11 PHP Statement and Ending Lines ► ► A statement in PHP is an executable line of code, which generally consist of a function and an argument. ► ► Notice that the PHP statement in the past example is terminated with a semi- colon ‘;’ ► ► All statements in PHP are terminated with ; http://arief.ismy.web.id

12 12 Switching Modes <? if( …….. ) { ?> You are using PHP <? } else { ?> You are not using PHP <? } ?> http://arief.ismy.web.id

13 13 Comments ► ► Why do we concern ourselves with comments so much? ► ► because without them, understanding scripts would be difficult. <? //C style comment /* C multi line comment */ ?> http://arief.ismy.web.id

14 14 PHP Types ► ► Basic data types ► ► – Integer - Used for whole numbers ► ► – Float (also double) - Used for real numbers ► ► – String - Used for strings of characters ► ► – Boolean – Used for true or false values ► ► – Array - Used to store multiple data items ► ► – Object - Used for storing instances of classes ► ► Dynamic typing ► ► – Don't have to declare types ► ► – Automatic conversion done ► ► – Supports typecasting eg. $total = (float) $sum; ► ► – Variable variables eg $$varname = 5; http://arief.ismy.web.id

15 15 Variables in PHP <? $x = false; // boolean $x = true; $x = 10; // decimal $x = 1.45; // Floating point $x = 0x1A; // hexadecimal $x = "PHP's site \n"; // PHP’s site and a new line $x[1] = 10 // array of decimals $x[2]["num"] = "xx"; // a two dimensional array ?> Type Casting <?<? $bool = true; print (int)$bool; // 1 ?> http://arief.ismy.web.id

16 16 Output to Browser Several different ways: ► ► print(); is a function that will print the contents of an argument to the screen.   Ex. print ("Here is an argument.");   Ex. Print (" It can be anything. "); ► ► Echo is not a function; it is a language construct, so doesn’t need parentheses.   Ex. echo " It can be a single word. "; http://arief.ismy.web.id

17 17 Predefined Variables ► ► PHP has a number of predefined variables. ► ► Predefined variables are always capitalized. ► ► $GLOBALS contains names and values of all predefined variables. ► ► Create a PHP file called predefined.php and insert: <?php echo " "; print_r ($GLOBALS); echo " "; ?> ► ► Save it then view in browser. http://arief.ismy.web.id

18 18 Global Variables ► ► Storing form data in simple variables is a major security risk, as users can easily guess variable names by looking at forms. ► ► We have register_globals turned off, as do most security minded hosting companies. ► ► So, form variables and data are stored in global variables $_POST or $_GET, based on your form method.   Ex. isavailable as $_POST['email']; or $_GET['email']; http://arief.ismy.web.id

19 19 Constants ► ► A constant is a special data type in PHP ► ► Unlike a variable they maintain their value throughout the life of a script. ► ► Since constants aren't variables, they do not begin with a $. ► ► Cannot be changed once set.   Good for values you don't want to inadvertently change by mixing up = with ==. ► ► Rule of thumb is to name constants in ALLCAPS. http://arief.ismy.web.id

20 20 Constants ► ► Use define(); function to create a constant:   define('FIRSTNAME', ‘John'); ► ► Constants don't expand within quotes as variables do.   echo "Hello FIRSTNAME"; //prints "Hello FIRSTNAME"   echo "Hello“.FIRSTNAME; //prints “Hello John” http://arief.ismy.web.id

21 21 Check if a Constant is Defined ► ► Use the defined() function to check if a constant is defined defined('CONSTANT_NAME')   Returns true if constant is defined   Example: if (defined('FIRSTNAME')){ echo 'Welcome'.FIRSTNAME. '!'; } else { echo 'You must give your name.'; } http://arief.ismy.web.id

22 22 PHP Operators + Addition - Subtraction * Multiplication / Division % Modulus & And | OR ^ Xor. add string (concatenate) http://arief.ismy.web.id

23 23 Numerical Function Addition   $a = 1 + 1; // sets $a to 2   $a+= 4; // adds 4 to $a   $a++; // adds 1 to $a Subtraction   $a = 10 - 5; # sets $a to 5   $a -= 6; # subtracts 6 from $a   $a--; # subtracts 1 from $a http://arief.ismy.web.id

24 24 Numerical Function Multiplication   $a = 2 * 3; // sets $a to 6   $a *= 10; // multiplies $a by 10 Division   $a = 10 / 3; // sets $a to 3.3333   $a /= 2; // halves $a Modulus   $a = 10 % 3; // sets $a to 1   $a %= 2; // sets $a to modulus 2 of itself http://arief.ismy.web.id

25 25 PHP Info ► ► Type your Code, save as info.php Exercise 1 This is the plain HTML text <?php phpinfo(); ?> ► ► Upload in a webserver   C:\xampp\htdocs\YourName ► ► View from Browser   http://localhost/NamaAnda/info.php http://arief.ismy.web.id

26 26 Pertemuan 13 MySQL Last Updated: 15 th May 2010 By M. Arief http://arief.ismy.web.id

27 27 Objectives ► To learn how to prepare a MySQL database for use with PHP ► To learn how to store, retrieve, and update data in a MySQL database http://arief.ismy.web.id

28 28 Which Database Systems? ► ► PHP works with a variety of databases that include:   Oracle   SQL Server   Access   Ingres   MySQL ► ► We will use MySQL since it is simple to use, free and very popular. http://arief.ismy.web.id

29 29 PHP-MySQL http://arief.ismy.web.id

30 30 PHP-MySQL ► ► Within MySQL, use Structured Query Language (SQL), to access database ► ► Embed SQL within PHP scripts and use predefined function http://arief.ismy.web.id

31 31 mysql_connect() and mysql_close() ► ► mysql_connect() establishes a connection to a MySQL server. ► ► It takes 3 parameters.   The address of the server   The username for that db account   The password ► ► $conn = mysql_connect("195.251.218.103", "user", "pass"); ► ► mysql_close() closes the connection to the database server. http://arief.ismy.web.id

32 32 mysql_select_db() ► ► mysql_select_db() selects a specific database so any queries you make are against this database. mysql_select_db("dbname",$conn); http://arief.ismy.web.id

33 33 mysql_query() ► ► mysql_query() executes a specific query using the database connection identifier. ► ► It sends a line of SQL to the MySQL server to be processed. ► ► This is the key command for interacting with the database. ► ► In our example the results that are returned are stored in the variable $result. http://arief.ismy.web.id

34 34

35 35 mysql_result() ► ► mysql_result() is used to traverse the result set returned from a query: mysql_result($result,0,"first"); ► ► Go to the first row of the result set $result, which is numbered 0, and return the value of the specified fields “first”. http://arief.ismy.web.id

36 36

37 37 Example: The Contacts Database Name Type Length Description idINT6A unique identifier for each record firstVARCHAR15The person's first name lastVARCHAR15The person's last name phoneVARCHAR20The person's phone number MobileVARCHAR20The person's mobile number faxVARCHAR20The person's fax number emailVARCHAR30The person's e-mail address webVARCHAR30The person's web address

38 38 Create The Contacts Database: setup.php <?$user="username";$password="password";$database="database";mysql_connect(localhost,$user,$password); @mysql_select_db($database) or die( "Unable to select database"); $query="CREATE TABLE contacts ( id int(6) NOT NULL auto_increment, first varchar(15) NOT NULL, last varchar(15) NOT NULL, phone varchar(20) NOT NULL, mobile varchar(20) NOT NULL, fax varchar(20) NOT NULL, email varchar(30) NOT NULL, web varchar(30) NOT NULL, PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))"; mysql_query($query);mysql_close();?>

39 39 Insert Data: Form add.html First Name: First Name: Last Name: Last Name: Phone: Phone: Mobile: Mobile: Fax: Fax: E-mail: E-mail: Web: Web: </form>

40 40 Insert Data: insert.php <?$username="username";$password="password";$database="your_database";$first=$_POST['first'];$last=$_POST['last'];$phone=$_POST['phone'];$mobile=$_POST['mobile'];$fax=$_POST['fax'];$email=$_POST['email'];$web=$_POST['web'];mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query = "INSERT INTO contacts VALUES ('','$first','$last','$phone','$mobile','$fax','$email','$web')"; mysql_query($query);mysql_close();?>

41 41 Output Data: output.php <?$username="username";$password="password";$database="your_database";mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query="SELECT * FROM contacts"; $result=mysql_query($query);$num=mysql_numrows($result);mysql_close();

42 42 Output Data: output.php echo " Database Output "; $i=0; while ($i < $num) { $first=mysql_result($result,$i,"first");$last=mysql_result($result,$i,"last");$phone=mysql_result($result,$i,"phone");$mobile=mysql_result($result,$i,"mobile");$fax=mysql_result($result,$i,"fax");$email=mysql_result($result,$i,"email");$web=mysql_result($result,$i,"web"); echo " $first $last Phone: $phone Mobile: $mobile Fax: $fax E-mail: $email Web: $web "; $i++;}?>

43 43 Output Data: table format, outputtable.php <tr> Name Name Phone Phone Mobile Mobile Fax Fax E-mail E-mail Website Website </tr><?$i=0; while ($i < $num) { $first=mysql_result($result,$i,"first");$last=mysql_result($result,$i,"last");$phone=mysql_result($result,$i,"phone");$mobile=mysql_result($result,$i,"mobile");$fax=mysql_result($result,$i,"fax");$email=mysql_result($result,$i,"email");$web=mysql_result($result,$i,"web");?>

44 44 Output Data: table format <tr> ">E-mail ">E-mail ">Website ">Website </tr><?$i++;} echo " ";

45 45 Update Data $id=$_POST['id'];$username="username";$password="password";$database="your_database";mysql_connect(localhost,$username,$password); $query=" SELECT * FROM contacts WHERE id='$id'"; $result=mysql_query($query);$num=mysql_numrows($result);mysql_close();

46 46 Update Data $i=0; while ($i < $num) { $first=mysql_result($result,$i,"first");$last=mysql_result($result,$i,"last");$phone=mysql_result($result,$i,"phone");$mobile=mysql_result($result,$i,"mobile");$fax=mysql_result($result,$i,"fax");$email=mysql_result($result,$i,"email");$web=mysql_result($result,$i,"web"); Space For Code ++$i;}

47 47 Update Data: Space for Code "> "> First Name: "> First Name: "> Last Name: "> Last Name: "> Phone Number: "> Phone Number: "> Mobile Number: "> Mobile Number: "> Fax Number: "> Fax Number: "> E-mail Address: "> E-mail Address: "> Web Address: "> Web Address: "> </form>

48 48 Update Data: updated.php $ud_id=$_POST['ud_id'];$ud_first=$_POST['ud_first'];$ud_last=$_POST['ud_last'];$ud_phone=$_POST['ud_phone'];$ud_mobile=$_POST['ud_mobile'];$ud_fax=$_POST['ud_fax'];$ud_email=$_POST['ud_email'];$ud_web=$_POST['ud_web'];$username="username";$password="password";$database="your_database";mysql_connect(localhost,$username,$password); $query="UPDATE contacts SET first='$ud_first', last='$ud_last', phone='$ud_phone', mobile='$ud_mobile', fax='$ud_fax', email='$ud_email', web='$ud_web' WHERE id='$ud_id'"; mysql_query($query); echo "Record Updated"; mysql_close();

49 49 Others Selecting Pieces of Data: ► $query="SELECT * FROM contacts WHERE last='$searchlast'"; ► $result=mysql_query($query); Error Tapping: ► if ($num==0) { echo "The database contains no contacts yet"; } else { Output Loop } Ordering Data: ► SELECT * FROM contacts ORDER BY last ASC

50 50 Others Efficiency: ► dbinfo.inc.php ► <? ► $username="databaseusername"; ► $password="databasepassword"; ► $database="databasename"; ► ?> ► include("dbinfo.inc.php");


Download ppt "1 Pertemuan 13 PHP-MySQL Last Updated: 15 th May 2010 By M. Arief"

Similar presentations


Ads by Google