Pengantar Teknologi Internet W14: Server Scripting & Database.

Slides:



Advertisements
Similar presentations
PHP II Interacting with Database Data. The whole idea of a database-driven website is to enable the content of the site to reside in a database, and to.
Advertisements

Manipulating MySQL Databases with PHP. PHP and mySQL2 Objectives Connect to MySQL from PHP Learn how to handle MySQL errors Execute SQL statements with.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Objectives Connect to MySQL from PHP
MySQL and PHP By Trevor Adams.
PHP and MySQL Web Development tMyn1 PHP and MySQL Web Development When you install PHP, you can select from a number of extensions. The MySQL support in.
Introduction to C Programming
1 CS428 Web Engineering Lecture 23 MySQL Basics (PHP - VI)
SJSU CS157B Dr. Lee1  2004 Jenny Mitchell Two Useful Tools You Can’t Live Without by Jenny Mitchell SJSU CS157B Section PHP and MySQL.
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
Application Development Description and exemplification of server-side scripting language for server connection, database selection, execution of SQL queries.
What is MySQL? MySQL is a database. The data in MySQL is stored in database objects called tables. A table is a collections of related data entries and.
© Yanbu University College YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College Module 6:WEB SERVER AND SERVER SIDE SCRPTING,
2010/11 : [1]Building Web Applications using MySQL and PHP (W1)PHP Recap.
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
INTERNET APPLICATION DEVELOPMENT For More visit:
Advanced Database Management System Lab no. 11. SQL Commands (for MySQL) –Update –Replace –Delete.
Chapter 7 PHP Interacts with Ms. Access (Open DataBase Connectivity (ODBC))
PHP – MySQL Extensions. Table used in most examples CREATE TABLE product ( rowID INT NOT NULL AUTO_INCREMENT, productid VARCHAR(8) NOT NULL, name VARCHAR(25)
INTERNET APPLICATION DEVELOPMENT PRACTICAL ON CONNECTING TO MYSQL.
PHP Flow Control Loops, Functions, Return, Exit, Require, Try...Catch Software University SoftUni Team Technical Trainers.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
NMED 3850 A Advanced Online Design January 26, 2010 V. Mahadevan.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
Introduction to MySQL Lab no. 10 Advance Database Management System.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
PHP MySQL. SQL: Tables CREATE TABLE tablename { fieldname type(length) extra info,... } Extra info: –NULL (allows nulls in this field) –Not NULL (null.
School of Computing and Information Systems CS 371 Web Application Programming PHP – Forms, Cookies, Sessions and Database.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Lec_6 Manipulating MySQL Databases with PHP PHP Programming with MySQL.
Chapter 6 PHP Interacts with Mysql Database. Introduction In PHP, there is no consolidated interface. Instead, a set of library functions are provided.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
1. Connecting database from PHP 2. Sending query 3. Fetching data 4. Persistent connections 5. Best practices.
Lecture 10 – MYSQL and PHP (Part 2)
PHP+MySQL Integration. Connecting to databases One of the most common tasks when working with dynamic webpages is connecting to a database which holds.
MySQL Database Connection
1 Chapter 4 – Breaking It Up: Functions spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
Web-Based Database Programming with PHP. Dept. of Computing Science, University of Aberdeen2 In this lecture you will learn PHP Basics PHP functions –To.
COMP An Introduction to Computer Programming : University of the West Indies COMP6015 An Introduction to Computer Programming Lecture 05.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
CHAPTER 9 PHP AND MYSQL. A POSSIBLE SITE CONFIGURATION Application Folder index.php includes (folder)header.phpfooter.phpstyle.cssmodel (folder)mysqli_connect.php.
CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Address: Course Page:
PHP PHP: Hypertext Preprocesor Personal Home Page Tools.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting PHP & MySQL.
PHP Database connectivity Connecting with RDBMS and editing, adding, and deleting databases therein are all done through PHP functions.
PHP Database Processing CIS 1715 Web Technologies.
Controlling Web Site Access Using Logins CS 320. Basic Approach HTML form a php page that collects the username and password  Sends them to second PHP.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
NMD202 Web Scripting Week5. What we will cover today PHP & MySQL Displaying Dynamic Pages Exercises Modifying Data PHP Exercises Assignment 1.
Accessing mySQL relational database. MySQL database.  Today, we will attempt and open a connection to the MySQL server.  We need to specify the database.
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
CSC 405: Web Application Engineering II8.1 Web programming using PHP What have we learnt? What have we learnt? Underlying technologies of database supported.
PHP Reusing Code and Writing Functions 1. Function = a self-contained module of code that: Declares a calling interface – prototype! Performs some task.
Creating FunctionstMyn1 Creating Functions Function can be divided into two groups: –Internal (built in) functions –User-defined functions.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
1 PHP and MySQL Web Development When you install PHP, you can select from a number of extensions. The MySQL support in PHP consists of a number of functions.
Chapter 19 PHP Part III Credits: Parts of the slides are based on slides created by textbook authors, P.J. Deitel and H. M. Deitel by Prentice Hall ©
Author: truong toan thinh
ISC440: Web Programming 2 Server-side Scripting PHP 3
PHP: Database connection
Web Programming– UFCFB Lecture
‘break’ break ends execution of the current for, foreach, while, do-while or switch structure break accepts an optional numeric argument which tells it.
PHP AND MYSQL.
Presentation transcript:

Pengantar Teknologi Internet W14: Server Scripting & Database

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

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 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 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 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 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 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 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 recursion levels as it can smash the stack and cause a termination of the current script. Warning: avoid recursive function/method calls with over recursion levels as it can smash the stack and cause a termination of the current script.

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 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 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 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 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 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 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 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 Returning Values function square($num) { return $num * $num; return $num * $num;} echo square(4); // outputs '16'.

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

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 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 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 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 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 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 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 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 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 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 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 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 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 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());