1 Pertemuan 13 PHP-MySQL Last Updated: 15 th May 2010 By M. Arief
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
3 References ► ► ►
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 ► 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.
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
6 PHP History
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
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.
9 PHP Tag Style ► ► XML Style: ► ► ► ► Short Style: ► ► ► ► Script Style: ► ► PHP Code In Here
10 Embedding PHP in HTML Search results for " "
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 ;
12 Switching Modes <? if( …….. ) { ?> You are using PHP <? } else { ?> You are not using PHP <? } ?>
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 */ ?>
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;
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 ?>
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. ";
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.
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[' ']; or $_GET[' '];
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.
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”
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.'; }
22 PHP Operators + Addition - Subtraction * Multiplication / Division % Modulus & And | OR ^ Xor. add string (concatenate)
23 Numerical Function Addition $a = 1 + 1; // sets $a to 2 $a+= 4; // adds 4 to $a $a++; // adds 1 to $a Subtraction $a = ; # sets $a to 5 $a -= 6; # subtracts 6 from $a $a--; # subtracts 1 from $a
24 Numerical Function Multiplication $a = 2 * 3; // sets $a to 6 $a *= 10; // multiplies $a by 10 Division $a = 10 / 3; // sets $a to $a /= 2; // halves $a Modulus $a = 10 % 3; // sets $a to 1 $a %= 2; // sets $a to modulus 2 of itself
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
26 Pertemuan 13 MySQL Last Updated: 15 th May 2010 By M. Arief
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
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.
29 PHP-MySQL
30 PHP-MySQL ► ► Within MySQL, use Structured Query Language (SQL), to access database ► ► Embed SQL within PHP scripts and use predefined function
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(" ", "user", "pass"); ► ► mysql_close() closes the connection to the database server.
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);
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.
34
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”.
36
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 VARCHAR30The person's address webVARCHAR30The person's web address
38 Create The Contacts Database: setup.php 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, 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 Insert Data: Form add.html First Name: First Name: Last Name: Last Name: Phone: Phone: Mobile: Mobile: Fax: Fax: Web: Web: </form>
40 Insert Data: insert.php or die( "Unable to select database"); $query = "INSERT INTO contacts VALUES ('','$first','$last','$phone','$mobile','$fax','$ ','$web')"; mysql_query($query);mysql_close();?>
41 Output Data: output.php or die( "Unable to select database"); $query="SELECT * FROM contacts"; $result=mysql_query($query);$num=mysql_numrows($result);mysql_close();
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");$ =mysql_result($result,$i," ");$web=mysql_result($result,$i,"web"); echo " $first $last Phone: $phone Mobile: $mobile Fax: $fax $ Web: $web "; $i++;}?>
43 Output Data: table format, outputtable.php <tr> Name Name Phone Phone Mobile Mobile Fax Fax 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");$ =mysql_result($result,$i," ");$web=mysql_result($result,$i,"web");?>
44 Output Data: table format <tr> "> "> ">Website ">Website </tr><?$i++;} echo " ";
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 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");$ =mysql_result($result,$i," ");$web=mysql_result($result,$i,"web"); Space For Code ++$i;}
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: "> Address: "> Address: "> Web Address: "> Web Address: "> </form>
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_ =$_POST['ud_ '];$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', ='$ud_ ', web='$ud_web' WHERE id='$ud_id'"; mysql_query($query); echo "Record Updated"; mysql_close();
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 Others Efficiency: ► dbinfo.inc.php ► <? ► $username="databaseusername"; ► $password="databasepassword"; ► $database="databasename"; ► ?> ► include("dbinfo.inc.php");