33
Pengantar Pengantar Teknologi Teknologi Internet Internet W14: W14: Server Scripting & Server Scripting & Database Database

Pengantar Teknologi Internet W14: Server Scripting & Database

Embed Size (px)

Citation preview

Page 1: Pengantar Teknologi Internet W14: Server Scripting & Database

Pengantar Pengantar Teknologi Teknologi InternetInternet

W14:W14:Server Scripting & DatabaseServer Scripting & Database

Page 2: Pengantar Teknologi Internet W14: Server Scripting & Database

2

ObjectivesObjectives

Functions:Functions: Global functionsGlobal functions User defined functionsUser defined functions MySQL libraryMySQL library

Page 3: Pengantar Teknologi Internet W14: Server Scripting & Database

3

Global FunctionsGlobal Functions By default all functions can be accessed By default all functions can be accessed

globally throughout the scriptglobally throughout the script For example, in a file called library.php:For example, in a file called library.php:

function echo_newline($strText) {function echo_newline($strText) {echo “$strText<br/>”;echo “$strText<br/>”;

}}

The above function will be available in any The above function will be available in any script by including it using this syntax:script by including it using this syntax: include “library.php”;include “library.php”;

Page 4: Pengantar Teknologi Internet W14: Server Scripting & Database

4

User-defined FunctionUser-defined Function

Syntax:Syntax:

function foo($arg_1, $arg_2, /* ..., */ $arg_n)function foo($arg_1, $arg_2, /* ..., */ $arg_n)

{{

echo "Example function.\n";echo "Example function.\n";

return $retval;return $retval;

}}

arg_1 .. arg_n arg_1 .. arg_n The arguments or parameters The arguments or parameters A function may or may not return the value to the A function may or may not return the value to the

callercaller

Page 5: Pengantar Teknologi Internet W14: Server Scripting & Database

5

FunctionFunction

Any valid PHP code may appear inside Any valid PHP code may appear inside a function, even other functions and a function, even other functions and class definitions. class definitions.

Function names follow the same rules Function names follow the same rules as other labels in PHP. as other labels in PHP. A valid function name starts with a letter or A valid function name starts with a letter or

underscore, followed by any number of underscore, followed by any number of letters, numbers, or underscores. letters, numbers, or underscores.

As a regular expression, it would be As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*. 9_\x7f-\xff]*.

Page 6: Pengantar Teknologi Internet W14: Server Scripting & Database

6

Conditional FunctionConditional Function$makefoo = true;

bar();

if ($makefoo) {

function foo()

{

echo "I don't exist until program execution reaches me.\n";

}

}

if ($makefoo) foo();

function bar()

{

echo "I exist immediately upon program start.\n";

}

Page 7: Pengantar Teknologi Internet W14: Server Scripting & Database

7

Function within FunctionFunction within Functionfunction foo() function foo() {{ function bar() function bar() {{ echo "I don't exist until foo() is called.\n";echo "I don't exist until foo() is called.\n"; }}}}

/* We can't call bar() yet since it doesn't exist. *//* We can't call bar() yet since it doesn't exist. */

foo();foo();

/* Now we can call bar(), foo()'s processesing has/* Now we can call bar(), foo()'s processesing has made it accessible. */made it accessible. */

bar();bar();

Page 8: Pengantar Teknologi Internet W14: Server Scripting & Database

8

Function Function

All functions and classes in PHP All functions and classes in PHP have the global scope - they can be have the global scope - they can be called outside a function even if they called outside a function even if they were defined inside and vice versa. were defined inside and vice versa.

PHP does not support function PHP does not support function overloading, nor is it possible to overloading, nor is it possible to undefine or redefine previously-undefine or redefine previously-declared functions. declared functions.

Page 9: Pengantar Teknologi Internet W14: Server Scripting & Database

9

Recursive FunctionRecursive Function

It is a function that calling itself.It is a function that calling itself. PHP supports this recursive function PHP supports this recursive function

through its stackable memory through its stackable memory managementmanagement

Warning: avoid recursive Warning: avoid recursive function/method calls with over 100-function/method calls with over 100-200 recursion levels as it can smash 200 recursion levels as it can smash the stack and cause a termination of the stack and cause a termination of the current script.the current script.

Page 10: Pengantar Teknologi Internet W14: Server Scripting & Database

10

Recursive FunctionRecursive Function

function recursion($a)function recursion($a)

{{

if ($a < 20) {if ($a < 20) {

echo "$a\n";echo "$a\n";

recursion($a + 1);recursion($a + 1);

}}

}}

recursion(15);recursion(15);

Page 11: Pengantar Teknologi Internet W14: Server Scripting & Database

11

Function ArgumentsFunction Arguments Information may be passed to functions via the Information may be passed to functions via the

argument list, which is a comma-delimited list of argument list, which is a comma-delimited list of expressions. expressions.

PHP supports passing arguments :PHP supports passing arguments : by value (the default), by value (the default), passing by reference, passing by reference, and default argument values. and default argument values.

Variable-length argument lists are supported only Variable-length argument lists are supported only in PHP 4 and later; see Variable-length argument in PHP 4 and later; see Variable-length argument lists and the function references for lists and the function references for func_num_args(), func_get_arg(), and func_num_args(), func_get_arg(), and func_get_args() for more information.func_get_args() for more information.

Page 12: Pengantar Teknologi Internet W14: Server Scripting & Database

12

Passing Array to a Passing Array to a FunctionFunction

function takes_array($input)function takes_array($input){{ echo "$input[0] + $input[1] = ", $input[0]+echo "$input[0] + $input[1] = ", $input[0]+

$input[1];$input[1];}}

$data = array(2, 4, 5, 7);$data = array(2, 4, 5, 7);takes_array($data);takes_array($data);

// what will be the output?// what will be the output?

Page 13: Pengantar Teknologi Internet W14: Server Scripting & Database

13

Passing by ReferencePassing by Reference

By default, function arguments are passed by By default, function arguments are passed by value (so that if you change the value of the value (so that if you change the value of the argument within the function, it does not get argument within the function, it does not get changed outside of the function). changed outside of the function).

If you wish to allow a function to modify its If you wish to allow a function to modify its arguments, you must pass them by arguments, you must pass them by reference. reference.

If you want an argument to a function to If you want an argument to a function to always be passed by reference, you can always be passed by reference, you can prepend an ampersand (&) to the argument prepend an ampersand (&) to the argument name in the function definition.name in the function definition.

Page 14: Pengantar Teknologi Internet W14: Server Scripting & Database

14

Passing by ReferencePassing by Reference

function add_some_extra(&$string)function add_some_extra(&$string)

{{

$string .= 'and something extra.';$string .= 'and something extra.';

}}

$str = 'This is a string, ';$str = 'This is a string, ';

add_some_extra($str);add_some_extra($str);

echo $str;echo $str;

// outputs 'This is a string, and something extra.'// outputs 'This is a string, and something extra.'

Page 15: Pengantar Teknologi Internet W14: Server Scripting & Database

15

Default Argument ValuesDefault Argument Values

function makecoffee($type = "cappuccino")function makecoffee($type = "cappuccino")

{{

return "Making a cup of $type.\n";return "Making a cup of $type.\n";

}}

echo makecoffee();echo makecoffee();

echo makecoffee(null);echo makecoffee(null);

echo makecoffee("espresso");echo makecoffee("espresso");

Page 16: Pengantar Teknologi Internet W14: Server Scripting & Database

16

Default Argument ValuesDefault Argument Valuesfunction makecoffee($types = array("cappuccino"), function makecoffee($types = array("cappuccino"),

$coffeeMaker = NULL)$coffeeMaker = NULL){{

$device = is_null($coffeeMaker) ? "hands" : $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;$coffeeMaker;

return "Making a cup of ".join(", ", $types)." return "Making a cup of ".join(", ", $types)." with with $device.\n";$device.\n";

}}

echo makecoffee();echo makecoffee();echo makecoffee(array("cappuccino", "lavazza"), echo makecoffee(array("cappuccino", "lavazza"),

"teapot");"teapot");

Page 17: Pengantar Teknologi Internet W14: Server Scripting & Database

17

Incorrect Default ValuesIncorrect Default Values Any defaults should be on the right side of Any defaults should be on the right side of

any non-default arguments; otherwise, any non-default arguments; otherwise, things will not work as expected.things will not work as expected.

function makeyogurt($type = "acidophilus", $flavour)function makeyogurt($type = "acidophilus", $flavour){{ return "Making a bowl of $type $flavour.\n";return "Making a bowl of $type $flavour.\n";}}

echo makeyogurt("raspberry"); // won't work as echo makeyogurt("raspberry"); // won't work as expectedexpected

Page 18: Pengantar Teknologi Internet W14: Server Scripting & Database

18

Returning ValuesReturning Values

function square($num)function square($num)

{{

return $num * $num;return $num * $num;

}}

echo square(4); // outputs '16'.echo square(4); // outputs '16'.

Page 19: Pengantar Teknologi Internet W14: Server Scripting & Database

19

Returning “Multiple” Returning “Multiple” ValuesValues

function small_numbers()function small_numbers()

{{

return array (0, 1, 2);return array (0, 1, 2);

}}

list ($zero, $one, $two) = small_numbers();list ($zero, $one, $two) = small_numbers();

Page 20: Pengantar Teknologi Internet W14: Server Scripting & Database

20

Returning a ReferenceReturning a Reference

To return a reference from a function, you To return a reference from a function, you have to use the reference operator & in have to use the reference operator & in both the function declaration and when both the function declaration and when assigning the returned value to a variable.assigning the returned value to a variable.

function &returns_reference()function &returns_reference()

{{

return $someref;return $someref;

}}

$newref =& returns_reference();$newref =& returns_reference();

Page 21: Pengantar Teknologi Internet W14: Server Scripting & Database

21

Variable FunctionVariable Function

If a variable name has parentheses If a variable name has parentheses appended to it, PHP will look for a appended to it, PHP will look for a function with the same name as function with the same name as whatever the variable evaluates to, whatever the variable evaluates to, and will attempt to execute it. and will attempt to execute it.

Among other things, this can be Among other things, this can be used to implement :used to implement : callbacks, callbacks, function tables, function tables, and many othersand many others

Page 22: Pengantar Teknologi Internet W14: Server Scripting & Database

22

Variable FunctionVariable Functionfunction foo() {function foo() { echo "In foo()<br />\n";echo "In foo()<br />\n";}}

function bar($arg = '')function bar($arg = ''){{ echo "In bar(); argument was '$arg'.<br />\n";echo "In bar(); argument was '$arg'.<br />\n";}}

$func = 'foo';$func = 'foo';$func(); // This calls foo()$func(); // This calls foo()

$func = 'bar';$func = 'bar';$func('test'); // This calls bar()$func('test'); // This calls bar()

Page 23: Pengantar Teknologi Internet W14: Server Scripting & Database

23

Variable Method Variable Method ExampleExampleclass Fooclass Foo

{{ function Variable()function Variable() {{ $name = 'Bar';$name = 'Bar'; $this->$name(); // This calls the Bar() $this->$name(); // This calls the Bar()

methodmethod }} function Bar()function Bar() {{ echo "This is Bar";echo "This is Bar"; }}}}

$foo = new Foo();$foo = new Foo();$funcname = "Variable";$funcname = "Variable";$foo->$funcname(); // This calls $foo->Variable()$foo->$funcname(); // This calls $foo->Variable()

Page 24: Pengantar Teknologi Internet W14: Server Scripting & Database

24

Internal Built-in Internal Built-in FunctionFunction

PHP comes standard with many functions PHP comes standard with many functions and constructs. and constructs.

There are also functions that require specific There are also functions that require specific PHP extensions compiled in otherwise you'll PHP extensions compiled in otherwise you'll get fatal "undefined function" errors. get fatal "undefined function" errors. to use image functions such as to use image functions such as

imagecreatetruecolor(), you'll need your PHP imagecreatetruecolor(), you'll need your PHP compiled with GD support. compiled with GD support.

to use mysql_connect() you'll need your PHP to use mysql_connect() you'll need your PHP compiled in with MySQL support. compiled in with MySQL support.

There are many core functions that are There are many core functions that are included in every version of PHP like the included in every version of PHP like the string and variable functions. string and variable functions.

Page 25: Pengantar Teknologi Internet W14: Server Scripting & Database

25

MySQL Functions MySQL Functions RevisitedRevisited

How to connect to a database:How to connect to a database:

// variant 1: using IP / name// variant 1: using IP / name

$link = mysql_connect('localhost', 'mysql_user', $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');'mysql_password');

if (!$link) {if (!$link) {

die('Could not connect: ' . mysql_error());die('Could not connect: ' . mysql_error());

}}

echo 'Connected successfully';echo 'Connected successfully';

mysql_close($link);mysql_close($link);

Page 26: Pengantar Teknologi Internet W14: Server Scripting & Database

26

mysql_pconnect()mysql_pconnect()

Establishes a persistent connection to a Establishes a persistent connection to a MySQL server. MySQL server.

mysql_pconnect() acts very much like mysql_pconnect() acts very much like mysql_connect() with two major differences. mysql_connect() with two major differences. First, when connecting, the function would first First, when connecting, the function would first

try to find a (persistent) link that's already open try to find a (persistent) link that's already open with the same host, username and password. If with the same host, username and password. If one is found, an identifier for it will be returned one is found, an identifier for it will be returned instead of opening a new connection. instead of opening a new connection.

Second, the connection to the SQL server will not Second, the connection to the SQL server will not be closed when the execution of the script ends. be closed when the execution of the script ends. Instead, the link will remain open for future use Instead, the link will remain open for future use (mysql_close() will not close links established by (mysql_close() will not close links established by mysql_pconnect()). mysql_pconnect()).

Page 27: Pengantar Teknologi Internet W14: Server Scripting & Database

27

Select a DatabaseSelect a Database

mysqlselect_db():mysqlselect_db(): Sets the current active database on the server Sets the current active database on the server

that's associated with the specified link that's associated with the specified link identifier. Every subsequent call to identifier. Every subsequent call to mysql_querymysql_query()() will be made on the active database. will be made on the active database.

// make foo the current db// make foo the current db

$db_selected = mysql_select_db('foo', $link);$db_selected = mysql_select_db('foo', $link);

if (!$db_selected) {if (!$db_selected) {

die ('Can\'t use foo : ' . mysql_error());die ('Can\'t use foo : ' . mysql_error());

} }

Page 28: Pengantar Teknologi Internet W14: Server Scripting & Database

28

Query ExampleQuery Examplemysql_connect("localhost", "mysql_user", mysql_connect("localhost", "mysql_user",

"mysql_password") or"mysql_password") or die("Could not connect: " . mysql_error());die("Could not connect: " . mysql_error());mysql_select_db("mydb");mysql_select_db("mydb");

$result = mysql_query("SELECT id, name FROM $result = mysql_query("SELECT id, name FROM mytable");mytable");

while ($row = mysql_fetch_array($result, MYSQL_NUM)) while ($row = mysql_fetch_array($result, MYSQL_NUM)) {{

printf("ID: %s Name: %s", $row[0], $row[1]); printf("ID: %s Name: %s", $row[0], $row[1]); }}

mysql_free_result($result);mysql_free_result($result);

Page 29: Pengantar Teknologi Internet W14: Server Scripting & Database

29

Using AssociationUsing Association$sql = "SELECT id as userid, fullname, userstatus $sql = "SELECT id as userid, fullname, userstatus FROM sometableFROM sometable WHERE userstatus = 1";WHERE userstatus = 1";

$result = mysql_query($sql);$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result)) {while ($row = mysql_fetch_assoc($result)) { echo $row["userid"];echo $row["userid"]; echo $row["fullname"];echo $row["fullname"]; echo $row["userstatus"];echo $row["userstatus"];}}

Page 30: Pengantar Teknologi Internet W14: Server Scripting & Database

30

QueryQuery

For SELECT, SHOW, DESCRIBE, For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements EXPLAIN and other statements returning resultset, mysql_query() returning resultset, mysql_query() returns a resource on success, or returns a resource on success, or FALSE on error. FALSE on error.

For other type of SQL statements, For other type of SQL statements, UPDATE, DELETE, DROP, etc, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on mysql_query() returns TRUE on success or FALSE on error. success or FALSE on error.

Page 31: Pengantar Teknologi Internet W14: Server Scripting & Database

31

QueryQuery

Use Use mysql_num_rows()mysql_num_rows() to find out to find out how many rows were returned for a how many rows were returned for a SELECT statementSELECT statement

Use Use mysql_affected_rows()mysql_affected_rows() to find to find out how many rows were affected by out how many rows were affected by a DELETE, INSERT, REPLACE, or a DELETE, INSERT, REPLACE, or UPDATE statement. UPDATE statement.

Page 32: Pengantar Teknologi Internet W14: Server Scripting & Database

32

Formulating QueryFormulating Query

This may be necessary to avoid SQL This may be necessary to avoid SQL Injection:Injection:

$query = sprintf("SELECT firstname, $query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",firstname='%s' AND lastname='%s'",

mysql_real_escape_string($firstname),mysql_real_escape_string($firstname),

mysql_real_escape_string($lastname));mysql_real_escape_string($lastname));

// Perform Query// Perform Query

$result = mysql_query($query);$result = mysql_query($query);

Page 33: Pengantar Teknologi Internet W14: Server Scripting & Database

33

Insert IdInsert Id Retrieves the ID generated for an AUTO_INCREMENT column by Retrieves the ID generated for an AUTO_INCREMENT column by

the previous INSERT query. the previous INSERT query.

$link = mysql_connect('localhost', 'mysql_user', $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');'mysql_password');

if (!$link) {if (!$link) {   die('Could not connect: ' . mysql_error());   die('Could not connect: ' . mysql_error());}}

mysql_select_db('mydb');mysql_select_db('mydb');

mysql_query("INSERT INTO mytable (product) values mysql_query("INSERT INTO mytable (product) values ('kossu')");('kossu')");

printf("Last inserted record has id %d\n", printf("Last inserted record has id %d\n", mysql_insert_id());mysql_insert_id());