Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pengantar Teknologi Internet W14: Server Scripting & Database.

Similar presentations


Presentation on theme: "Pengantar Teknologi Internet W14: Server Scripting & Database."— Presentation transcript:

1 Pengantar Teknologi Internet W14: Server Scripting & Database

2 2 Objectives Functions: Functions: Global functions Global functions User defined functions User defined functions MySQL library MySQL library

3 3 Global Functions By default all functions can be accessed globally throughout the script By default all functions can be accessed globally throughout the script For example, in a file called library.php: For example, in a file called library.php: function echo_newline($strText) { echo “$strText ”; } The above function will be available in any script by including it using this syntax: The above function will be available in any script by including it using this syntax: include “library.php”; include “library.php”;

4 4 User-defined Function Syntax: Syntax: function foo($arg_1, $arg_2, /*..., */ $arg_n) { echo "Example function.\n"; echo "Example function.\n"; return $retval; return $retval;} arg_1.. arg_n  The arguments or parameters arg_1.. arg_n  The arguments or parameters A function may or may not return the value to the caller A function may or may not return the value to the caller

5 5 Function Any valid PHP code may appear inside a function, even other functions and class definitions. Any valid PHP code may appear inside a function, even other functions and class definitions. Function names follow the same rules as other labels in PHP. Function names follow the same rules as other labels in PHP. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. A valid function name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

6 6 Conditional 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"; }

7 7 Function within Function 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. */ foo(); /* Now we can call bar(), foo()'s processesing has made it accessible. */ made it accessible. */bar();

8 8 Function All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa. All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa. PHP does not support function overloading, nor is it possible to undefine or redefine previously- declared functions. PHP does not support function overloading, nor is it possible to undefine or redefine previously- declared functions.

9 9 Recursive Function It is a function that calling itself. It is a function that calling itself. PHP supports this recursive function through its stackable memory management PHP supports this recursive function through its stackable memory management Warning: avoid recursive function/method calls with over 100-200 recursion levels as it can smash the stack and cause a termination of the current script. Warning: avoid recursive function/method calls with over 100-200 recursion levels as it can smash the stack and cause a termination of the current script.

10 10 Recursive Function function recursion($a) { if ($a < 20) { if ($a < 20) { echo "$a\n"; echo "$a\n"; recursion($a + 1); recursion($a + 1); }}recursion(15);

11 11 Function Arguments Information may be passed to functions via the argument list, which is a comma-delimited list of expressions. Information may be passed to functions via the argument list, which is a comma-delimited list of 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 in PHP 4 and later; see Variable-length argument lists and the function references for func_num_args(), func_get_arg(), and func_get_args() for more information. Variable-length argument lists are supported only in PHP 4 and later; see Variable-length argument lists and the function references for func_num_args(), func_get_arg(), and func_get_args() for more information.

12 12 Passing Array to a Function function takes_array($input) { echo "$input[0] + $input[1] = ", $input[0]+$input[1]; echo "$input[0] + $input[1] = ", $input[0]+$input[1];} $data = array(2, 4, 5, 7); takes_array($data); // what will be the output?

13 13 Passing by Reference By default, function arguments are passed by value (so that if you change the value of the argument within the function, it does not get changed outside of the function). By default, function arguments are passed by value (so that if you change the value of the argument within the function, it does not get changed outside of the function). If you wish to allow a function to modify its arguments, you must pass them by reference. If you wish to allow a function to modify its arguments, you must pass them by reference. If you want an argument to a function to always be passed by reference, you can prepend an ampersand (&) to the argument name in the function definition. If you want an argument to a function to always be passed by reference, you can prepend an ampersand (&) to the argument name in the function definition.

14 14 Passing by Reference function add_some_extra(&$string) { $string.= 'and something extra.'; $string.= 'and something extra.';} $str = 'This is a string, '; add_some_extra($str); echo $str; // outputs 'This is a string, and something extra.'

15 15 Default Argument Values function makecoffee($type = "cappuccino") { return "Making a cup of $type.\n"; return "Making a cup of $type.\n";} echo makecoffee(); echo makecoffee(null); echo makecoffee("espresso");

16 16 Default Argument Values function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL) { $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker; return "Making a cup of ".join(", ", $types)." with $device.\n"; } echo makecoffee(); echo makecoffee(array("cappuccino", "lavazza"), "teapot");

17 17 Incorrect Default Values Any defaults should be on the right side of any non- default arguments; otherwise, things will not work as expected. Any defaults should be on the right side of any non- default arguments; otherwise, things will not work as expected. 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 expected

18 18 Returning Values function square($num) { return $num * $num; return $num * $num;} echo square(4); // outputs '16'.

19 19 Returning “Multiple” Values function small_numbers() { return array (0, 1, 2); return array (0, 1, 2);} list ($zero, $one, $two) = small_numbers();

20 20 Returning a Reference To return a reference from a function, you have to use the reference operator & in both the function declaration and when assigning the returned value to a variable. To return a reference from a function, you have to use the reference operator & in both the function declaration and when assigning the returned value to a variable. function &returns_reference() { return $someref; return $someref;} $newref =& returns_reference();

21 21 Variable Function If a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. If a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement : Among other things, this can be used to implement : callbacks, callbacks, function tables, function tables, and many others and many others

22 22 Variable Function function foo() { echo "In foo() \n"; echo "In foo() \n";} function bar($arg = '') { echo "In bar(); argument was '$arg'. \n"; echo "In bar(); argument was '$arg'. \n";} $func = 'foo'; $func(); // This calls foo() $func = 'bar'; $func('test'); // This calls bar()

23 23 Variable Method Example class Foo { function Variable() function Variable() { $name = 'Bar'; $name = 'Bar'; $this->$name(); // This calls the Bar() method $this->$name(); // This calls the Bar() method } function Bar() function Bar() { echo "This is Bar"; echo "This is Bar"; }} $foo = new Foo(); $funcname = "Variable"; $foo->$funcname(); // This calls $foo->Variable()

24 24 Internal Built-in Function PHP comes standard with many functions and constructs. PHP comes standard with many functions and constructs. There are also functions that require specific PHP extensions compiled in otherwise you'll get fatal "undefined function" errors. There are also functions that require specific PHP extensions compiled in otherwise you'll get fatal "undefined function" errors. to use image functions such as imagecreatetruecolor(), you'll need your PHP compiled with GD support. to use image functions such as imagecreatetruecolor(), you'll need your PHP compiled with GD support. to use mysql_connect() you'll need your PHP compiled in with MySQL support. to use mysql_connect() you'll need your PHP compiled in with MySQL support. There are many core functions that are included in every version of PHP like the string and variable functions. There are many core functions that are included in every version of PHP like the string and variable functions.

25 25 MySQL Functions Revisited How to connect to a database: How to connect to a database: // variant 1: using IP / name $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: '. mysql_error()); die('Could not connect: '. mysql_error());} echo 'Connected successfully'; mysql_close($link);

26 26 mysql_pconnect() Establishes a persistent connection to a MySQL server. Establishes a persistent connection to a MySQL server. mysql_pconnect() acts very much like mysql_connect() with two major differences. mysql_pconnect() acts very much like mysql_connect() with two major differences. First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection. First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection. Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()). Second, the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use (mysql_close() will not close links established by mysql_pconnect()).

27 27 Select a Database mysqlselect_db(): mysqlselect_db(): Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database. Sets the current active database on the server that's associated with the specified link identifier. Every subsequent call to mysql_query() will be made on the active database. mysql_query() // make foo the current db $db_selected = mysql_select_db('foo', $link); if (!$db_selected) { die ('Can\'t use foo : '. mysql_error()); die ('Can\'t use foo : '. mysql_error());}

28 28 Query Example mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: ". mysql_error()); die("Could not connect: ". mysql_error());mysql_select_db("mydb"); $result = mysql_query("SELECT id, name FROM mytable"); 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);

29 29 Using Association $sql = "SELECT id as userid, fullname, userstatus FROM sometable FROM sometable WHERE userstatus = 1"; WHERE userstatus = 1"; $result = mysql_query($sql); while ($row = mysql_fetch_assoc($result)) { echo $row["userid"]; echo $row["userid"]; echo $row["fullname"]; echo $row["fullname"]; echo $row["userstatus"]; echo $row["userstatus"];}

30 30 Query For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. For other type of SQL statements, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error. For other type of SQL statements, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

31 31 Query Use mysql_num_rows() to find out how many rows were returned for a SELECT statement Use mysql_num_rows() to find out how many rows were returned for a SELECT statement Use mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement. Use mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

32 32 Formulating Query This may be necessary to avoid SQL Injection: This may be necessary to avoid SQL Injection: $query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE 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 $result = mysql_query($query);

33 33 Insert Id Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query. Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query. $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: '. mysql_error()); } mysql_select_db('mydb'); mysql_query("INSERT INTO mytable (product) values ('kossu')"); printf("Last inserted record has id %d\n", mysql_insert_id());


Download ppt "Pengantar Teknologi Internet W14: Server Scripting & Database."

Similar presentations


Ads by Google