Download presentation
1
INTRODUCTION TO PHP/mySQL I
FTSM Lab / May 2011
2
Goal Provide the basic knowledge of PHP programming
Explain how you can code and run PHP scripts Creating dynamic pages Basic database interactions – read, insert, update and delete data Basic session management PHP Application packages
3
Structure HTML/ XHTML PHP Database CSS JavaScript
4
HTML/JavaScript/CSS http://www.w3schools.com
HTML, JavaScript and CSS tutorials
5
Client-server architecture
6
What is PHP? PHP = ‘Hypertext PreProcessor’
Originally created by Rasmus Lerdorf in 1994 The main implementation of PHP is now produced by The PHP Group (de facto standard for PHP) - Open-source (access to source code and free distribution right), server-side scripting language
7
How PHP works
8
How to run PHP scripts PHP on Windows Method1 IIS FastCGI + PHP mySQL
Apache PHP Method3 WAMP Packages Method4 Web Hosting
9
Webhosting Webhosting information
10
WAMP Packages - XAMPP http://www.apachefriends.org/en/index.html
Version for Windows includes: Apache, MySQL, PHP, Perl, phpMyAdmin, JpGraph, FileZilla FTP Server, SQLite etc.
11
WAMP Packages - WAMPServer
Version for Windows includes: Apache, PHP, Mysql (version 64 and 32 bits), PhpMyadmin, SQLBuddy, XDebug, webGrind, XDC
12
PHP Scripts Basic syntaxes, data types, variable, control structures, arrays, function
13
PHP DATABASE VARIABLES BASIC SYNTAX DATA TYPE CONTROL STATEMENTS
FUNCTION DATABASE CONNECT/ READ INSERT UPDATE DELETE SESSION PHP PACKAGES
14
PHP code <?php … … ?> Structurally similar to C/C++
All PHP statements end with a semi-colon Each PHP script must be enclosed in the reserved PHP tag <?php … … ?>
15
PHP code - comments Standard C, C++, and shell comment symbols
// C++ and Java-style comment # Shell-style comments /* C-style comments These can span multiple lines */
16
PHP code - output Use ‘echo’ or ‘print’
Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP <?php $nilai = 25; // Numerical variable $ayat = “Hello”; // String variable echo $ayat; // Outputs Hello echo $nilai, $ayat; // Outputs 25Hello echo “5x5=”,$nilai; // Outputs 5x5=25 echo “5x5=$nilai”; // Outputs 5x5=25 echo ‘5x5=$nilai’; // Outputs 5x5=$nilai ?>
17
PHP – escape character If the string has a set of double quotation marks that must remain visible, use the \ [backslash] before the quotation marks to ignore and display them. <?php $jab=“\”PHP\””; print $jab; //”PHP” ?>
18
PHP code - variables PHP variables must begin with a “$” sign
Case-sensitive ($var != $VAR != $vAr) Global and locally-scoped variables Global variables can be used anywhere Local variables restricted to a function or class Certain variable names reserved by PHP Form variables ($_POST, $_GET) Server variables ($_SERVER)
19
PHP code – variables <?php
$nilai = 25; //Numerical variable $ayat = “Hello”; //String variable $nilai = ($nilai * 7); //Multiplies variable nilai by 7 ?>
20
PHP code - operations <?php $a=30; $b=5; $total=$a+$b;
print $total; //35 print “<p>Jumlah ialah $total</p>”; // Jumlah ialah 35 print $a-$b; //25 print $a*$b; //150 print $a/$b; //6 print $a+=$b; //35 print $a%$b; //0 ?>
21
PHP code – strings function
Use a period to join strings into one. <?php $string1=“Hello”; $string2=“PHP”; $string3=$string1 . “ ” . $string2; print $string3; //Hello PHP ?>
22
PHP – Control Statements
Control structures similar with JavaScript/C++ if, elseif, else switch, case while for foreach
23
PHP - if, elseif, else <?php $markah = 90; if ($markah >= 80)
echo “Lulus dengan cemerlang"; elseif ($markah >= 40) echo “Lulus"; else echo “Gagal"; ?>
24
PHP control – switch … switch ($jantina){ case “L”: echo “Lelaki"; break; case “P”: echo “Perempuan"; break; default: echo “Tiada input jantina"; } …
25
PHP control – while loops
$nombor = 1; while ($nombor!=10){ print “Bilangan $nombor”; $nombor++; } ?>
26
PHP control – for loops <?php for ($n = 1; $n<=10; $n++){
print “Bilangan $n”; } ?>
27
PHP control – foreach loops
$numbers = array("one","two","three"); foreach ($numbers as $value) { echo $value . "<br />"; } ?>
28
PHP arrays Three kind of arrays:
Numeric array - An array with a numeric index Associative array - An array where each ID key is associated with a value Multidimensional array - An array containing one or more arrays
29
PHP – numeric arrays <?php //numeric array
$cars = array("Saab","Volvo","BMW",“Ford"); echo $cars[2]; //BMW ?>
30
PHP – associative arrays
$umur = array ("Raju"=>32, "Gopal"=>34, "Samy" => 36); //same as $umur[‘Raju’]=32… echo $umur[‘Gopal’]; //34 ?>
31
PHP - multi dimensional arrays
$kump = array ("Merah"=> array ("Ali", "Raju", "Joan"), "Biru"=> array ("Abu", "Jason", "Lin"), "Hijau" => array ("David", "Jim", "Mary"); echo $kump [‘Merah’][2]; //Joan echo $kump [‘Hijau’][0]; //David ?>
32
PHP array functions array_push() – adds element/s to an array <?php
$a=array("Dog","Cat"); array_push($a,"Horse","Bird"); print_r($a); /*Array ([0]=>Dog [1]=>Cat [2]=>Horse [3]=>Bird) */ ?>
33
PHP array functions array_pop() – deletes last element in an array
$a=array("Dog","Cat","Horse"); array_pop($a); print_r($a); // Array ([0]=>Dog [1]=>Cat) ?>
34
PHP array functions unset() – destroy a variable
$array = array(0, 1, 2, 3); unset($array[2]); /* array(3) { [0]=>int(0) [1]=>int(1) [3]=>int(3) } */
35
PHP - functions Functions MUST be defined before they can be called
Function headers are of the format function function_name ($var1, $var2…){ … } Function names are not case sensitive
36
PHP - functions <?php // This is a function
function darab($arg1, $arg2){ $arg3 = $arg1 * $arg2; return $arg3; } echo darab(12,3); // 36 ?>
37
PHP - Using external files
Using external files for: HTML codes Structure – template files like headers, footers Functions – separate file to store all functions Config – separate configuration settings in different file
38
PHP – include and require
Four functions: include() include_once() require() require_once() Generates warnings when the function doesn’t work Generates errors and halts scripts when the function doesn’t work
39
PHP - include Using “include” to include external files <?php
include “header.php” Include “tarikh.php” include “menubar.php” … ?> <?php print “Tarikh hari ini ialah $date2”; ?>
40
PHP References http://www.php.net <- php home page
<- php download page php <- php installation manual <- php online tutorial
41
Database and SQL SQL, MySQL, phpMyAdmin, creating database and tables
42
SQL SQL – Structured Query Language
SQL can be used to access and manipulate databases SELECT * FROM pelajar SELECT * FROM pelajar WHERE NoMatrik=‘A123456’
43
SELECT nama FROM pelajar
SQL Queries Query database for specific information and have a recordset returned from table SELECT nama FROM pelajar nama Jalil Gopal Ah Meng
44
SQL Keywords SELECT – select from tables FROM – specifies tables
WHERE – specifies criteria INSERT – inserts data into table UPDATE – updates data in table DELETE – deletes data in table CREATE – create new table DROP – delete existing table
45
SQL Keywords Usage SELECT * FROM pelajar Output: select all columns from table pelajar SELECT nama, nomatrik FROM pelajar Output: select columns nama and nomatrik from table pelajar WHERE nomatrik=‘A12345’ Output: select columns nama, nomatrik from table pelajar where row nomatrik equals ‘A12345’
46
SQL Keywords Usage INSERT INTO pelajar (nomatrik, nama, jabatan, kumpulan) VALUES (‘A12365’, ‘Hashim’, ‘4’, ‘9’) Action: insert specified value to table pelajar, creating new row DELETE FROM pelajar WHERE nomatrik=‘A12369’ Action: select row from table pelajar where nomatrik as specified and delete the row
47
SQL Keywords Usage UPDATE pelajar SET nama = ‘Hisham’ WHERE nama = ‘Hashim’ AND nomatrik = ‘A12365’ Action: update specified row to table pelajar
48
MySQL MySQL - "My Structured Query Language“
Created by Michael Widenius from TcX (Sweden) in 1994 Open-source, relational database management system MySQL is used in web applications and acts as the database component of the WAMP/LAMP Used in free software projects (e.g. WordPress, Joomla)
49
MySQL and WAMP/LAMP Download at
50
MySQL Interfaces Interfaces to manage and browse database easily
phpMyAdmin heidiSQL MySQL-Front SQLyog
51
phpMyAdmin
52
Creating Database CREATE DATABASE databasename
53
Creating Tables Some of MySQL data types: Type Description
CHAR [length] Fixed-length, 0 to 255 characters long VARCHAR [length] Variable-length, 0 to 255 characters long TEXT String, maximum 65,535 characters INT [length] millions to 2,147 millions DATE YYYY-MM-DD format TIME HH:MM:SS
54
Creating Tables Choose a suitable name and create table
Identify columns names Identify data types Identify suitable MySQL data type Identify suitable length
55
Creating Tables Creating table for a guestbook application
56
Creating Tables Identifying column general data type Column name Type
Number NAMA Text TARIKH Date/time KOMEN
57
Table: guestbook Column name Type MySQL data type ID Number INT NAMA
Text VARCHAR [40] TARIKH Date/time DATETIME KOMEN TEXT
59
guestbook ID NAMA EMAIL TARIKH KOMEN 1 Simon simon@yahoo.com
:40:48 Excellent website! Well done! 2 Azizi :20:48 Sila lawati laman web saya: azizi.com.my 3 Wei Yoong :45:12 Still waiting for the updates :D
60
PHP and MySQL Read, insert, update and delete data using PHP
61
DELETE DATA CREATE CONNECTION CLOSE CONNECTION INSERT DATA READ DATA UPDATE DATA
62
PHP Creating & Closing Connection
Use mysql_connect() and mysql_close() $con = mysql_connect (servername, username, password); if (!$con) { die('Could not connect: ' . mysql_error()); } … mysql_close($con);
63
PHP Selecting Database
Use mysql_select_db() … $con = mysql_connect (servername, username, password); mysql_select_db (databasename, $con);
64
PHP Displaying data Use mysql_query() to run SQL
The return result are usually in array form $result = mysql_query ("SELECT * FROM guestbook"); while($row = mysql_fetch_array ($result)) { echo $row[‘NAMA'] . “-" . $row[‘ '] . ”-” . row[‘TARIKH'] . “-" . $row[‘KOMEN']; }
65
PHP Inserting data Use mysql_query() …
//run query mysql_query("INSERT INTO guestbook (ID, NAMA, , TARIKH, KOMEN) VALUES (5, ‘Jason', NOW(), ‘Website yang bagus!’)"); …
66
PHP Inserting data //Create query
$qry = "INSERT INTO guestbook (ID, NAMA, , TARIKH, KOMEN) VALUES (5, ‘Jason', NOW(), ‘Website yang bagus!’)”; //Run query mysql_query($qry); …
67
PHP Inserting data from Form
HTML FORM PHP
68
PHP Inserting data from Form
69
PHP Inserting data from Form
… $sql="INSERT INTO guestbook (NAMA, , TARIKH, KOMEN) VALUES ('$_POST[nama]', '$_POST[ ]‘, '$_POST[tarikh]‘, '$_POST[komen]')"; …
70
PHP Displaying data in table
… echo "<table>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row[‘NAMA'] . "</td>"; echo "<td>" . $row[‘ '] . "</td>"; echo "<td>" . $row[‘TARIKH'] . "</td>"; echo "<td>" . $row[‘KOMEN'] . "</td>"; echo "</tr>"; } echo "</table>"; …
71
PHP Updating data Use UPDATE /SET /WHERE to update data
mysql_query (“UPDATE guestbook SET = WHERE NAMA = ‘Simon‘ "); }
72
PHP Deleting data Use DELETE FROM /WHERE to delete data from database
… mysql_query (“DELETE FROM guestbook WHERE Nama = ‘Simon‘ "); …
73
Update/Delete in Form Modify display table form to incorporate update/delete functions //make a link at the end of each table row for UPDATE and DELETE … echo “<td>”; echo "<a href='delete.php?cmd=delete&id=$id‘>Delete</a>"; echo “</td><td>”; echo "<a href=‘update.php?&id=$id‘>Delete</a>"; echo "<br>"; if($_GET["cmd"]=="delete") { … }
74
HTTP Requests GET Gets/retrieves information from server (e.g retrieve an image, fetch search results) Sends information as part of URL (visible, 2048 chars limit) Cached, bookmark-able POST Posts/sends data (e.g login information, post form data) Submitted data is hidden (invisible) Non-cached, non-bookmark-able
75
Update Process Select data by primary key using SQL SELECT
Show data in HTML form to modify elements Use SQL UPDATE to update data
76
PHP Session Management
User sessions
77
Sessions Using session identifier in server to locate and store user data Advantage over cookies: More secure – all data stored in server Not browser/computer dependent – some users reject cookies/turn off Store more data than cookie Use session_start() and $_SESSION[variable]
78
Sessions … session_start(); If (isset($_SESSION[‘user_id’])){ …
//login process session_start(); $_SESSION[‘user_id’] = A11201; … //reset session array $_SESSION = array(); //delete session session_destroy();
79
PHP Application Packages
Installing packages, customizing packages
80
PHP packages Useful and easy to install PHP applications Phpmyadmin
Joomla modx phpBB Wordpress Mediawiki zend
81
phpMyadmin MySQL interface Deployment: Download from site
Unzip to web document root
82
Joomla Multi-user CMS Deployment: Download and unzip in
web document root Launch install script
83
modx Multi-user CMS
84
phpBB Bulletin board
85
Wordpress Blogging application -
86
MediaWiki Wiki -
87
Zend
88
THANK YOU
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.