Professional PHP Programming phần 4 ppt

86 220 0
Professional PHP Programming phần 4 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

PHP Support for Database Connectivity PHP supports API’s for accessing large numbers of databases like Oracle, Sybase, PostgreSQL, MySQL etc. The PHP programs, to access the data from the database on the fly, can use these API's. Open Database Connectivity (ODBC) is a standard Application Programming Interface (API) for accessing a database that has PHP support. This can be used for writing generic database applications. By generic I mean that the same application code will work for all the Databases supporting the ODBC standard. There will be a performance overhead with ODBC, if the database doesn’t support ODBC natively, and moreover ODBC being a generic standard supports only generic features. If you want to use some specific feature of a database, then one should use the language API of that database. In this section we will cover PHP API’s for accessing MySQL databases. You can look at the PHP documentation for APIs to access other databases. Lets briefly cover the features of MySQL before we look into the PHP API’s. MySQL Database MySQL is a small, compact, easy to use database server, ideal for small and medium sized applications. It is a client/ server implementation that consists of a server daemon mysqld and many different client programs. It is available on a variety of UNIX platforms, Windows NT and Windows 95/98. On UNIX platforms it uses threading, which makes it a high performance and highly scalable database server. The main features of a MySQL database server are described below. Standards Supported MySQL supports entry-level ANSI SQL92 and ODBC level 0-2 SQL standard. Language Support The database server mysqld can issue error messages in Czech, Dutch, English, Estonian, French, German, Hungarian, Italian, Norwegian Nynorsk, Polish, Portuguese, Spanish and Swedish. MySQL by default uses the ISO-8859-1 (Latin1) character set for data and sorting. The character set used for data and sorting can be changed while compiling the sources. Programming Language API’s for Clients to Access the Database MySQL database applications can be written in a set of languages like C, Perl, PHP etc. Large Tables MySQL stores each table in the database as a separate file in the database directory. The maximum size of a table can be between a minimum of 4GB and the Operating System limit on the maximum file size. Speed, Robustness and Ease of Use MySQL is about three to four times faster than many other commercial databases. MySQL is also very easy to manage. You do not need a trained Database Administrator for administering a MySQL Installation. TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Cost Advantage MySQL is an open source relational database. It is distributed free of cost for UNIX and OS/2 platforms and for Microsoft platforms you need to get a license after a trial period of 30 days. So with MySQL you get a cost advantage over other commercial relational databases. Database Features not present in MySQL Though MySQL is a comprehensive database system, you should be aware of its limitations, which are detailed below. Most of the web based database applications can be written without using these features. But if your application needs these features to be present in the back end database, then you should consider using other commercial databases like SQL Server, Oracle etc., which support these features. Sub-selects Sub-selects are not supported in MySQL. For Example, the following statement returns data about employees whose salaries exceed their department average: SELECT deptno, ename, sal FROM emp x WHERE sal > (SELECT AVG(sal) FROM emp WHERE x.deptno = deptno) ORDER BY deptno; Most of the SQL statements which use sub selects can be rewritten as SQL statements without sub select. Complex SQL statements using sub selects, which can’t be rewritten to SQL statements without these sub selects should (create and) store the value of the sub query in a temporary table, and access the temporary table in the main query. Transactions A Transaction is a logical unit of work that comprises one or more SQL statements executed by a single user. A transaction ends when it is explicitly committed or rolled back by that user. For example in a Banking Application, when a bank customer transfers money from a savings account to a checking account, the transaction might consist of three separate operations: decrease the savings account, increase the checking account, and record the transaction in the transaction journal. When something prevents one of the statements in the transaction from executing (such as a hardware failure), the other statements of the transaction must be undone. Committing a transaction makes permanent the changes resulting from all SQL statements in the transaction. Rolling back a transaction retracts any of the changes resulting from the SQL statements in the transaction. After a transaction is rolled back, the affected data is left unchanged as if the SQL statements in the transaction were never executed. Transactions are currently not supported in MySQL. MySQL supports LOCK_TABLES and TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com UNLOCK_TABLES commands to lock tables, which can be used by the thread to prevent interference by other threads for concurrency issues. MySQL does not support Row level locking of tables. LOCK_TABLES can lock multiple tables with the specified access i.e. Read/ write. Locks on a table get released when the thread holding the lock executes UNLOCK_TABLE command or when the thread holding the lock dies. Stored Procedures and Triggers A stored procedure is a set of SQL commands that are compiled and are stored in the server. Clients now can refer to the stored procedure, instead of reissuing the entire SQL commands. You get performance benefit by using stored procedures, because the SQL statements are already parsed and compiled in the server, and less data needs to be sent to the server from the client. A trigger is a stored procedure that is invoked when a particular event occurs. For example, a trigger can be set on a stock price table, the trigger gets fired after any UPDATE operation is done on that table. The trigger can be set to send e-mails to interested people (taken from another table) if the stock prices of any of the updated rows changes by 20%. However, MySQL does not have support for stored procedures and triggers. Foreign Keys Different tables in a relational database can be related by common columns, and the rules that govern the relationship of the columns must be maintained. Referential integrity rules guarantee that these relationships are preserved. The column included in the definition of the referential integrity constraint that reference to a primary key of another table is called a foreign key. For example, a Dept column of the Employees table is a foreign key that refers to the Dept column of the Departments Table. Any insert done on the Employee Table with the wrong Dept column value (i.e. Department does not exist) will fail. It means that there will be no employee entry in the Employee Table, which will have a department that does not exist. MySQL does not support foreign keys. However, the foreign key syntax in MySQL does exist, but only for compatibility with other database vendors, and it does not do anything. Views A view is a tailored presentation of the data contained in one or more table (or other views). A view takes the output of a query and treats it as a table; therefore, a view can be thought of as a "stored query" or a "virtual table". No storage is allocated to View. For example, in employee table, you want all the users (who are not managers) to see only the name, and employee-id fields of the Table. You can create a view on the table with the following SQL statement: Create View Employee_View as SELECT name, employee-id FROM Employee All the users (non-managers) can be given SELECT privilege on the Employee_View. Now they will only be able to access name, and employee-id fields of the Employee table. MySQL does not support views. TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com MySQL API Support in PHP mysql_connect Creates a connection to a MySQL Server. int mysql_connect(string [hostname [:port] [:/path_to_socket]], string [username], string [password]); The arguments for this function are given in the table below, and all of these are optional: Parameter Description Default hostname The name of the host running the database server. There is no need to specify this if the database and the web server are running on the same machine. "localhost" :port The port that the database server is using for listening to requests. Only needed if your setup uses a port different than the default for MySQL. ":3306" :/path_to_sock et The Unix socket that the server is using for listening to requests. ":/tmp/mysql.soc k" username The name of the user allowed to connect to the database server. The user that owns the web server process password The password for the user; if missing it is assumed empty. The first argument specifies the hostname (optionally port, else default port is assumed) or the UNIX domain socket, on which the MySQL server is listening for the client requests. If the PHP program and the database server are running on the same machine, then they can communicate using the UNIX domain socket. Note that all the SQL (and other) commands sent to the MySQL server using this connection will be executed with the privileges of the username. The function returns a link identifier (a positive number which references the connection) on success, or false on error. This link identifier will be used in all the function calls, which send requests to the MySQL server. If another mysql_connect call is made with the same arguments, a new connection will not be created to the server. The link identifier of the connection already open will be returned. The connection (between the PHP client program and the MySQL Server) will be closed when a mysql_close call is made, or when the PHP script exits. TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com mysql_pconnect Creates a persistent connection to a MySQL Server. int mysql_pconnect(string [hostname [:port] [:/path_to_socket]], string [username], string [password]); The function arguments and the return value are same as those for mysql_connect. The difference between mysql_pconnect and mysql_connect is that the connection created with mysql_pconnect is not closed when the PHP program exits or a mysql_close call is made. The PHP interpreter maintains the connection with the MySQL server. When a mysql_pconnect call is made, the PHP interpreter first finds out if there is an existing open connection with the same function arguments. If it finds one then the link identifier of the existing connection is returned, instead of creating a new connection. The mysql_pconnect function should be used in PHP applications where, over a short period of time, a large number of connections will be made to the MySQL server using the same username and password. mysql_pconnect saves the overhead of creating and closing a connection. Note that mysql_pconnect will work only if PHP is configured as a module in the web server. mysql_close This will end the connection with the MySQL server and is optional. int mysql_close(int [link_identifier]); Parameter Description Default link_identifie r The reference for the connection to be closed. The link identifier for the last connection opened. The mysql_close function returns true on success, or false on error. Note that mysql_close will not close persistent links generated using mysql_pconnect. mysql_create_db Creates a new database on the MySQL server. int mysql_create_db(string name, int [link_identifier]); Parameter Description Default name The name of the database to be created. link_identifie r The reference of the connection, on which the request will be sent to the Database Server. The link identifier for the last connection opened. TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com The name parameter is required, though the link_identifier is optional. The mysql_create_db() function returns true on success, or false on failure. Alternatively mysql_query can be used to send the Create Database SQL command to the MySQL server to create a new database. mysql_drop_db Drops (removes) a MySQL database. int mysql_drop_db(string database_name, int [link_identifier]); Parameter Description Default name The name of the database to be deleted link_identifie r The reference of the connection, on which the request will be sent to the Database Server. The link identifier for the last connection opened. The name parameter is required, though the link_identifier is optional. The function returns true on success, or false on failure. Alternatively mysql_query can be used to send the Drop Database SQL command to the MySQL server to delete a database. mysql_select_db Selects a database as the active database. int mysql_select_db(string database_name, int [link_identifier]); Parameter Description Default database_name The name of the database which is to become the active database link_identifie r The reference of the connection, on which the request will be sent to the Database Server. The link identifier for the last connection opened. If no connection is open, then the function tries to open a new connection using mysql_connect with default parameters. The database_name parameter is required, though the link_identifier is optional. The function returns true on success, or false on error. TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com All the SQL statements passed to the MySQL server will be made on the active database. mysql_query Sends the SQL statement to the MySQL server for execution. int mysql_query(string query, int [link_identifier]); Parameter Description Default query The SQL command to be sent to the MySQL server link_identifie r The reference of the connection, on which the SQL command will be sent to the Database Server. The link identifier for the last connection opened. If no connection is open, then the function tries to open a new connection using mysql_connect with default parameters. The query parameter is required, though the link_identifier is optional. The function returns a result identifier (positive integer) on success, or false on error. The result identifier contains the result of the execution of the SQL statement on the MySQL server. In the case of Data Definition Language (DDL) SQL statements (CREATE, ALTER, DROP), the result identifier will indicate success or failure. In the case of Data Manipulation Language (DML) SQL statements DELETE, INSERT, UPDATE), the result identifier can be used to find out the number of affected rows by using mysql_affected_rows() call, with the result identifier as an argument. With the DML statement SELECT, the result identifier will be an integer that corresponds to a pointer to the result set. This can be used to find the result of the SELECT statement with a mysql_result() call with the result identifier as an argument. For example, the following code creates a table named addressbook, which contains the addresses of people. Here the return value of mysql_query function is used to find whether the SQL command execution succeeded or failed. <HTML> <HEAD> <TITLE> Creating Table </TITLE> </HEAD> <BODY> <?php $userName ="php"; $password ="php"; TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com $hostName = "www.harawat.com"; $databaseName = "php"; $tableName = "addressbook"; SQL statement for creating a table $stmt = "CREATE TABLE %s(NAME CHAR(255), EMAIL CHAR(255), CITY CHAR(255), DESCRIPTION CHAR(255), TELEPHONE CHAR(255), ROWID INT PRIMARY KEY AUTO_INCREMENT)"; Function to print error messages. function printError($errorMesg) { printf("<BR> %s <BR>\n", $errorMesg); } Open a connection with the database server // Connect to the Database if (!($link=mysql_connect($hostName, $userName, $password))) { printError(sprintf("error connecting to host %s, by user %s", $hostName, $userName)); exit(); } Create the database $databaseName. // Create the $databaseName database if (!mysql_create_db($databaseName, $link)) { printError(sprintf("Error in creating %s database", $databaseName)); printError(sprintf("error:%d %s", mysql_errno($link), mysql_error($link))); exit(); } printf("<BR> Created Database %s <BR>\n", $databaseName); Make the created database $databaseName as active database. // Make $databaseName the active database if (!mysql_select_db($databaseName, $link)) { printError(sprintf("Error in selecting %s database", $databaseName)); printError(sprintf("error:%d %s", mysql_errno($link), mysql_error($link))); exit(); } Create the table address book. TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com // Create the table AddressBook if (!mysql_query(sprintf($stmt,$tableName), $link)) { printError(sprintf("Error in executing %s stmt", $stmt)); printError(sprintf("error:%d %s", mysql_errno($link), mysql_error($link))); exit(); } printf("<BR> Created Table %s.%s <BR>\n", $databaseName, $tableName); ?> </BODY> </HTML> mysql_db_query Sends the SQL statement to the MySQL server, along with the name of the active database. It is similar to mysql_query. int mysql_db_query(string database, string query, int [link_identifier]); Parameter Description Default database The name of the active database query The SQL command to be sent to the MySQL server link_identifie r The reference of the connection, on which the request will be sent to the Database Server. The link identifier for the last connection opened. If no connection is open, then the function tries to open a new connection using mysql_connect with default parameters. The database and query parameters are required, though the link_identifier is optional. The return values are same as in the case of mysql_db_query. For example, to SELECT all rows from the employee table in database1: $stmt = "SELECT * from employee"; $result = mysql_db_query("database1", $stmt, $linkId); Alternatively mysql_query can also be used by modifying the SQL statement $stmt = "SELECT * from database1.employee"; $result = mysql_query($stmt, $linkId); TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com mysql_list_dbs Lists databases available on the MySQL server. int mysql_list_dbs(int [link_identifier]); Parameter Description Default link_identifie r The reference for the connection on which the request will be sent to the Database Server. The link identifier for the last connection opened. If no connection is open, then the function tries to open a new connection using mysql_connect with default parameters. The link_identifier is optional. The function returns a result identifier on success, else false is returned on error. The mysql_tablename() function should be used to traverse the result identifier to get the list of databases. mysql_list_tables Lists all the tables in a MySQL database. int mysql_list_tables(string database, int [link_identifier]); Parameter Description Default database Name of the Database, whose list of tables will be returned. link_identifie r The reference for the connection on which the request will be sent to the Database Server. The link identifier for the last connection opened. If no connection is open, then the function tries to open a new connection using mysql_connect with default parameters. The database parameter is required, though the link_identifier is optional. The function returns a result identifier on success, else false is returned on error. The mysql_tablename() function should be used to traverse the result identifier to get the list of databases. mysql_num_rows Returns the number of rows in the result identifier (which contains the result of the executed SQL TEAM FLY PRESENTS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... All the PHP scripts connect to the MySQL database as user php $userName= "php" ; $password= "php" ; $databaseName = "php" ; // Database User Login // Database User Password // Database name Name of the table, in which addressbook is stored $tableName = "addressbook" ; ?> // Name of the table common .php This file contains common functions, which are used throughout the code < ?php // common .php // Common... page of the application ReturnToMain(); ?> search .php The script search .php is executed after the user clicks on the SEARCH button on the Search page The script is called with form variables $cn, $mail, $locality, $description, $telephonenumber describing the search criteria specified by the user . PHP Support for Database Connectivity PHP supports API’s for accessing large numbers of databases like Oracle, Sybase, PostgreSQL, MySQL etc. The PHP programs, to access. cover PHP API’s for accessing MySQL databases. You can look at the PHP documentation for APIs to access other databases. Lets briefly cover the features of MySQL before we look into the PHP API’s closed when the PHP program exits or a mysql_close call is made. The PHP interpreter maintains the connection with the MySQL server. When a mysql_pconnect call is made, the PHP interpreter

Ngày đăng: 12/08/2014, 23:23

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan