Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source,...

58
PHP/MySQL Tutorial Introduction to Database

Transcript of Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source,...

Page 1: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

PHP/MySQL TutorialIntroduction to Database

Page 2: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

What is PHP?PHP == ‘PHP Hypertext Preprocessor’Open-source, server-side scripting languageUsed to generate dynamic web-pagesPHP scripts reside between reserved PHP

tagsThis allows the programmer to embed PHP

scripts within HTML pages

Page 3: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

What is PHP (cont’d)Interpreted language, scripts are parsed at

run-time rather than compiled beforehandExecuted on the server-sideSource-code not visible by client

‘View Source’ in browsers does not display the PHP code

Various built-in functions allow for fast development

Compatible with many popular databases

Page 4: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

3(+1) Tier architecture

PHP script

Remote services

Web Server(Apache, IIS)

Browser(IE, FireFox,

Opera)

Desktop(PC or MAC)

Database

DatabaseServer

SQL

Client application

HTTP

HTML

Web Service

tables

DHTML

SMS

vision

touch

voice

SMS system

Page 5: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

PHP advantageAny 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 1Content

Page 5Content

Page 3Content

Page 2Content

Page 4Content

Header

Footer

Page 6: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

What does PHP code look like?Structurally similar to C/C++Supports procedural and object-oriented

paradigm (to some degree)All PHP statements end with a semi-colonEach PHP script must be enclosed in the

reserved PHP tag

<?php …?>

Page 7: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Comments in PHPStandard C, C++, and shell comment

symbols

// C++ and Java-style comment

# Shell-style comments

/* C-style comments These can span multiple lines */

Page 8: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Variables in PHPPHP variables must begin with a “$” signCase-sensitive ($Foo $foo $fOo)Global and locally-scoped variables

Global variables can be used anywhereLocal variables restricted to a function or

classCertain variable names reserved by PHP

Form variables ($_POST, $_GET)Server variables ($_SERVER)Etc.

Page 9: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Variable usage

<?php$foo = 25; // Numerical variable$bar = “Hello”; // String variable

$foo = ($foo * 7); // Multiplies foo by 7$bar = ($bar * 7); // Invalid expression ?>

Page 10: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

EchoThe PHP command ‘echo’ is used to

output the parameters passed to itThe typical usage for this is to send data

to the client’s web-browserSyntax

echo string arg1 [, string argn...]

Page 11: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Echo example

Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25

Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP

This is true for both variables and character escape-sequences (such as “\n” or “\\”)

<?php$foo = 25; // Numerical variable$bar = “Hello”; // String variable

echo $bar; // Outputs Helloecho $foo,$bar; // Outputs 25Helloecho “5x5=”,$foo; // Outputs 5x5=25echo “5x5=$foo”; // Outputs 5x5=25echo ‘5x5=$foo’; // Outputs 5x5=$foo?>

Page 12: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Arithmetic Operations

$a - $b // subtraction$a * $b // multiplication$a / $b // division$a += 5 // $a = $a+5

<?php$a=15;$b=30;$total=$a+$b;Print $total;Print “<p><h1>$total</h1>”;// total is 45

?>

Page 13: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

ConcatenationUse a period to join strings into one.

<?php$string1=“Hello”;$string2=“PHP”;$string3=$string1 . “ ” . $string2;Print $string3;?>

Hello PHP

Page 14: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Escaping the CharacterIf 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$heading=“\”Computer Science\””;Print $heading;?>

“Computer Science”

Page 15: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

PHP Control Structures

if (expr) statement

<?phpif ($a > $b) {

echo "a is bigger than b";$b = $a;

}?><?php

if ($a > $b) {echo "a is greater than b";

} else {echo "a is NOT greater than b";

}?>

Page 16: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

PHP Control Structuresif ($foo == 0) {

echo ‘The variable foo is equal to 0’;}else if (($foo > 0) && ($foo <= 5)) {

echo ‘The variable foo is between 1 and 5’;}else {

echo ‘The variable foo is equal to ‘.$foo;}

Page 17: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

PHP Control Structures<?php

switch ($i) {case "apple":

echo "i is apple";break;

case "bar":echo "i is bar";break;

case "cake":echo "i is cake";break;

default: echo ‘Enter correct option’;

}?>

Page 18: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Loopswhile (condition) {statements;}

<?php$count=0;While($count<3){

Print “hello PHP. ”;$count += 1;// $count = $count + 1;// or// $count++;

?>

hello PHP. hello PHP. hello PHP.

Page 19: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Loopsfor (expr1; expr2; expr3)

statement <?php

$i = 0;do {

echo $i;} while ($i > 0);

?>

Page 20: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Loops<?php

$arr = array(1, 2, 3, 4);foreach ($arr as $value) {

echo “$value \n”;}foreach ($arr as &$value) {

$value = $value * 2;} // $arr is now array(2, 4, 6, 8)unset($value);//break the

reference ?>

Page 21: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Loopsforeach ($arr as $key => $value) {

echo "Key:$key; Value:$value<br />\n";}

break ends execution of the current for, foreach, while, do-while or switch structure.

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

Page 22: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

ArraysAn array in PHP is actually an ordered map which

maps values to keys. An array can be thought of in many ways:

Linearly indexed array , list (vector), hash table (which is an implementation of a map), dictionary, collection, stack (LIFO), queue (FIFO)

Page 23: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

ArraysKinds of arrays:

numeric arrays. associative arrays. multi dimensional arrays.

Page 24: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

ArraysIn numeric arrays each key value corresponds to

numeric values.They can be divided into two categories

1.automatic numeric array index.2.manual array numeric index.

automatic numeric array index<?php $x=array(1,2,3); print_r($x);?>o/p: array(0=>1,1=>2,2=>3)

Page 25: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

ArraysManual array numeric index <?php $x[2]=10; $x[3]=50;//$x=array(2=>10,3=>50); echo $x[2]; echo $x[3];?>Associative arraysIn associated arrays each ID associated with its value <?php $x=array(“ab”=>1,”cd”=>2,”xy”=>3); print_r($x); ?>

Page 26: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

ArraysMultidimensional Arrays-An array contains one or

more arrays

<?php$z=array(array(10,20,30),array(40,50,60)); print_r($z);

?>

Array ( [0] => Array ( [0] => 10 [1] => 20 [2] => 30 )

[1] => Array ( [0] => 40 [1] => 50 [2] => 60 ) )

Page 27: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Arrays

<?php

$x=array(“ab”=>1,array(2,3,4),”cd”=>8);print_r($x);

?>

Array ( [“ab”] => 1 [0] => Array ( [0] => 2 [1] => 3 [2] => 4 ) [”cd”] => 8 )

Page 28: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Arrays<?php

$x=array(3=>4,array(2,3,4),5);print_r($x);

?>

Array ( [3] => 4 [4] => Array ( [0] => 2 [1] => 3 [2] => 4 ) [5] => 5 )

Page 29: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

ArraysArray operationssortksortrsortkrsortarray_mergearray_combinearray_intersect

Page 30: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Date Display$datedisplay=date(“yyyy/m/d”);print $datedisplay;

$datedisplay=date(“l, F J, Y”);print $datedisplay;

Wednesday, April 1, 2009

2009/4/1

Page 31: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Month, Day & Date Format Symbols

M JanF Januarym 01n 1

Day of Month d 01Day of Month J 1Day of Week l MondayDay of Week D Mon

Page 32: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Functions

Functions MUST be defined before then can be called

Function headers are of the format

Unlike variables, function names are not case sensitive

function functionName($arg_1, $arg_2, …, $arg_n)

Page 33: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Functions example<?php // This is a function

function foo($arg_1, $arg_2) { $arg_2 = $arg_1 * $arg_2;   return $arg_2;}

$result_1 = foo(12, 3); // Store the function echo $result_1; // Outputs 36echo foo(12, 3); // Outputs 36?>

Page 34: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Include Filesinclude “header.php”;include (“footer.php”);

This inserts files; the code in files will be inserted into current code.

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

Page 35: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Include FilesThe include_once statement includes and

evaluates the specified file during the execution of the script.

This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again.

The require_once statement is identical to require except PHP will check if the file has already been included, and if so, not include (require) it again

Page 36: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

PHP - Forms <?php

if ($_POST["submit"]) echo "<h2>You clicked Submit!</h2>"; else if ($_POST["cancel"]) echo "<h2>You clicked Cancel!</h2>";?>

<form action="form.php" method="post"> <input type="submit" name="submit" value="Submit"> <input type="submit" name="cancel" value="Cancel"></form>

Page 37: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

PHP - Forms <?php

…$term=$_REQUEST[“sterm”];…

?>

<form action="form.php" method="post"> <input type=“text" name=“sterm"

value=“<?= $term ?>"> </form>

Page 38: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

MySQL Connectivitymysql_connect()

The mysql_connect()function opens a non-persistent MySQL connection.

This function returns the connection on success, or FALSE and an error on failure. You can hide the error output by adding an '@' in front of the function name.

Syntaxmysql_connect(server,user,pwd,newlink,clientflag)

Page 39: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

MySQL ConnectivityParameter

Description

server Specifies the server to connect to

user Specifies the username to log in with.

pwd Specifies the password to log in with.

newlink If a second call is made to mysql_connect() with the same arguments, no new connection will be established; instead, the identifier of the already opened connection will be returned

clientflag •MYSQL_CLIENT_SSL - Use SSL encryption•MYSQL_CLIENT_COMPRESS - Use compression protocol•MYSQL_CLIENT_IGNORE_SPACE - Allow space after function names•MYSQL_CLIENT_INTERACTIVE - Allow interactive timeout seconds of inactivity before closing the connection

Page 40: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

MySQL ConnectivityExample:

<?php$con = mysql_connect("localhost","mysql_user","mysql_pwd");if (!$con){  die('Could not connect: ‘.mysql_error());}echo 'Connected successfully';mysql_close($con);

?>

Page 41: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

MySQL Connectivitymysql_close()

The mysql_close() function closes a non-persistent MySQL connection.

This function returns TRUE on success, or FALSE on failure.

Syntax:mysql_close(connection)

Parameter Description

connection Specifies the MySQL connection to close. If not specified, the last connection opened by mysql_connect() is used.

Page 42: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

MySQL Connectivitymysql_select_db()

The mysql_select_db() function sets the active MySQL database.

This function returns TRUE on success, or FALSE on failure.

Syntax:mysql_select_db(database,connection)

Parameter Description

database Required. Specifies the database to select.

connection Optional. Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.

Page 43: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

MySQL Connectivity<?php$con = mysql_connect("localhost", “root",

“admin");if (!$con){

die('Could not connect: '. mysql_error());}$db_selected = mysql_select_db("test_db",

$con);if (!$db_selected){

die ("Can\'t use test_db : “. mysql_error());

}mysql_close($con);

?>

Page 44: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

MySQL Connectivitymysql_query()

The mysql_query() function executes a query on a MySQL database.

This function returns the query handle for SELECT queries, TRUE/FALSE for other queries, or FALSE on failure.

Syntaxmysql_query(query,connection)

Parameter Description

query Required. Specifies the SQL query to send (should not end with a semicolon)

connection Optional. Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used.

Page 45: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

MySQL Connectivity<?php$con = mysql_connect("localhost",”root",”admin");if (!$con){  die('Could not connect: ' . mysql_error());}$sql = "CREATE DATABASE my_db";if (mysql_query($sql,$con)){  echo "Database my_db created";}else{  echo "Error creating database:" . mysql_error();}

?>

Page 46: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

MySQL Connectivity<?php$con = mysql_connect("localhost", “root",

“admin");if (!$con){

die('Could not connect: '. mysql_error());}$db_selected = mysql_select_db("test_db", $con);if (!$db_selected){

die ("Can\'t use test_db : “. mysql_error());}$sql="SELECT * FROM Person where name=‘$uname’";mysql_query($sql,$con); mysql_close($con);

?>

Page 47: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

MySQL Connectivitymysql_fetch_array()

The mysql_fetch_array() function returns a row from a recordset as an associative array and/or a numeric array.

This function gets a row from the mysql_query() function and returns an array on success, or FALSE on failure or when there are no more rows.

Syntaxmysql_fetch_array(data,array_type)

Page 48: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

MySQL Connectivity

Parameter

Description

data Required. Specifies which data pointer to use. The data pointer is the result from the mysql_query() function

array_type Optional. Specifies what kind of array to return.Possible values:•MYSQL_ASSOC - Associative array•MYSQL_NUM - Numeric array•MYSQL_BOTH - Default. Both associative and numeric array

Page 49: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

MySQL Connectivitymysql_fetch_row()

The mysql_fetch_row() function returns a row from a recordset as a numeric array.

This function gets a row from the mysql_query() function and returns an array on success, or FALSE on failure or when there are no more rows.

Syntaxmysql_fetch_row(data)

Parameter

Description

data Required. Specifies which data pointer to use. The data pointer is the result from the mysql_query() function

Page 50: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

MySQL Connectivity<?phpecho "<table>";while ($row = mysql_fetch_row($result)) {

echo "<tr><td>".$row[0] ."</td><td>".$row[1].

"</td><td>".$row[2]."</td><td>".$row[3]."</td></tr>";

}echo "</table>";

?>

Page 51: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

MySQL Connectivity<?phpecho "<table>";while ($row = mysql_fetch_array($result)) {

echo "<tr><td>{$row[‘ID’]} </td><td>{$row[1]}</td><td>{$row[2]}</td><td>

${row[‘mailid’]}</td></tr>";}echo "</table>";

?>

Page 52: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

CookiesThe setcookie() function is used to create

cookies. Should be called before <html> tag.setcookie(name, [value], [expire], [path], [domain], [secure]);

<?php setcookie("uname", $name, time()+36000); ?>

This sets a cookie named "uname" - that expires after ten hours.

Either a blank value or a time in the past makes the cookie expired.

Page 53: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

CookiesTo access a cookie, refer to the cookie name as a

variable or use $_COOKIE array. The isset() checks whether the cookie is set or not

<html> <body><?php if (isset($uname))// isset($_Cookie[$uname])

echo "Welcome " . $_Cookie[$uname]. "!<br />";

else echo "You are not logged in!<br />"; ?>

?></body> </html>

Page 54: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

CookiesBenefit of CookiesCookies are used for authenticating, tracking,

and maintaining specific information about users

Personolised home pagesElectronic shopping carts.

Page 55: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Why use sessionsA normal HTML website will not pass data

from one page to another All information is forgotten when a new page

is loaded Many websites need to pass user data from

one page to another for tasks like a shopping cart, which requires

data(the user's selected product) to be remembered from one page to the next

Using PHP sessions is one solution.

Page 56: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

SessionsThe session_start() function is used to

create a session. Should be called before <html> tag.

<?php session_start(); ?>

Page 57: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Sessions<?php session_start();

if (!isset($_SESSION['count'])) $_SESSION['count'] = 0;

else $_SESSION['count']++;

?>

Page 58: Introduction to Database. What is PHP? PHP == ‘PHP Hypertext Preprocessor’ Open-source, server-side scripting language Used to generate dynamic web-pages.

Sessionssession_unregister(´varname´);

unregisters a session variablesession_destroy() destroys a session