You do not need a trained Database Administrator for administering a MySQL Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com... link_identifie which the request wi
Trang 1PHP 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
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
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 2Cost 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
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
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 3UNLOCK_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 Deptcolumn of the Departments Table Any insert done on the Employee Table with the wrong Deptcolumn 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
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 4MySQL 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:
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.sock"
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
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 5mysql_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_pconnectcall 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]);
The mysql_close function returns true on success, or false on error Note that mysql_closewill 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]);
name The name of the database to be created
link_identifie
which the request will be sent to the The link identifier for the last connection
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 6The 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]);
name The name of the database to be deleted
link_identifie
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]);
database_name The name of the database which is to
become the active database
link_identifie
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
Trang 7All 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]);
query The SQL command to be sent to the
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
Trang 8$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
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 9// 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();
int mysql_db_query(string database, string query, int [link_identifier]);
database The name of the active database
query The SQL command to be sent to the
MySQL server
link_identifie
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";
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 10mysql_list_dbs
Lists databases available on the MySQL server
int mysql_list_dbs(int [link_identifier]);
link_identifie
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]);
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
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 11statement)
int mysql_num_rows(int result_identifier);
result_identifie
mysql_db_query, mysql_query, mysql_list_tables,
mysql_list_dbs
The result_identifier parameter is required, and this function is used when the query performed corresponded to a SELECT statement
mysql_tablename
Get the table/database name from the result identifier
string mysql_tablename(int result_identifier, int i);
result_identifie
mysql_list_tables, mysql_list_dbs
Open a connection with the Database Server
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 12if (!($link = mysql_connect($hostName, $userName, $password))) {
printf("<BR> error in connecting to the host %s <BR>\n", $hostName);
exit();
}
Get the list of Databases in the Server
// Get the list of Databases
if (!($listOfDbs = mysql_list_dbs($link))) {
printf("<BR> error in mysql_list_dbs, error %s <BR>\n", mysql_error($link)); exit();
}
printf("<b> Databases on %s </b> <br> <br>\n", $hostName);
// Get the list of Databases
$noOfDbs = 0;
Display the list of Databases
while ($noOfDbs < mysql_num_rows($listOfDbs)) {
printf(" %s <BR>\n", mysql_tablename($listOfDbs, $noOfDbs));
Retrieves the information about a table
int mysql_list_fields(string database_name, string table_name, int
[link_identifier]);
database_name The name of the database to which the
table belongs
table_name The name of the table about which to
list retrieve the information
link_identifie
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
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 13connection using
mysql_connect with
default parameters
The database_name and table_name parameters are required, though the link_identifier
is optional The function returns a result identifier on success, or false on error
The result identifier can be used with mysql_field_flags(), mysql_field_len(), mysql_field_name(), mysql_field_type() calls to get the information about a table mysql_list_fields call is useful in the program, where you don't know beforehand the columns (or data types) of the table
mysql_num_fields
Gets the number of fields in a result set
int mysql_num_fields(int result_identifier);
result_identifie
mysql_db_query, mysql_query, mysql_list_tables,
mysql_list_dbsThe result_identifier parameter is required The function returns the number of fields in the
result_identifier
mysql_field_len
Gets the length of a field
int mysql_field_len(int result_identifier, int field_offset);
result_identifie
mysql_db_query, mysql_query, mysql_list_tables,
Trang 14mysql_field_name
Retrieves the name of a field in the database
string mysql_field_name(int result_identifier, int field_index);
result_identifie
mysql_db_query, mysql_query, mysql_list_tables,
mysql_list_dbs
field_index The index for the field in the result
identifier
The result_identifier and field_index parameters are required The function returns the
name of the field at offset field_index in the result_identifier
mysql_field_type
Returns the data type of a given field
string mysql_field_type(int result_identifier, int field_index);
result_identifie
mysql_db_query, mysql_query, mysql_list_tables,
Retrieves the flags for a given field
string mysql_field_flags(int result_identifier, int field_index);
result_identifie
mysql_db_query, mysql_query, mysql_list_tables,
mysql_list_dbsSimpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 15field_index The index for the field in the result
Retrieves the name of the table to which a specific field belongs
string mysql_field_table(int result_identifier, int field_index);
result_identifie
r
The result identifier returned by mysql_db_query, mysql_query, mysql_list_tables,
mysql_list_dbs
field_index The index for the field in the result
identifier
The result_identifier and field_index parameters are required The function returns the
name of the table, for the field at offset field_index in the result_identifier
mysql_affected_rows
Retrieves the number of rows affected by a SQL query
int mysql_affected_rows(int [link_identifier] );
link_identifier The reference for the connection on
which the SQL query was sent to the Database Server
The link identifier for the last connection opened
The link_identifier parameter is optional The function returns the number of rows affected, in the previous SQL query
This call should be used to find out the number of rows inserted, updated or deleted by the previous SQL (INSERT, DELETE, REPLACE or UPDATE) query sent to the server If the last query was a DELETE without a WHERE clause (thus removing all records from a particular table), the function will return zero The number of rows returned by the SELECT SQL query should be found with
mysql_num_rows() function rather than with mysql_affected_rows()
mysql_insert_id
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 16executed INSERT SQL command on a table that contained an AUTO_INCREMENT column
int mysql_insert_id(int [link_identifier]);
link_identifier The reference for the connection on
which the INSERT SQL command was sent
The link identifier for the last connection opened
mysql_fetch_row
Retrieves the next row from the result identifier, as an enumerated array
array mysql_fetch_row(int result_identifier);
result_identifie
mysql_db_query, mysql_query, mysql_list_tables,
mysql_list_dbs
The result_identifier parameter is required The function returns an array (corresponding to the current row ), or false if there are no more rows
mysql_fetch_row() internally increments the internal row pointer field of the
result_identifier So each subsequent call of mysql_fetch_row() will return the next row from the result
mysql_data_seek
Sets the internal row pointer of the result identifier
int mysql_data_seek(int result_identifier, int row_number);
result_identifie
mysql_db_query, mysql_query, mysql_list_tables,
mysql_fetch_row will return row_number row
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 17The function returns true on success, or false on error
mysql_fetch_field
Retrieves the column information from the result set
object mysql_fetch_field(int result_identifier, int [field_offset]);
result_identifie
r
The result identifier returned by mysql_db_query, mysql_query, mysql_list_tables,
The result_identifier parameter is required, though field_index is optional The function returns an object describing the field at offset field_offset, in the result_identifier If the optional argument field_offset is not specified, then the next field that was not retrieved with mysql_fetch_field is returned
The returned object has the following properties:
❑ name: column name
❑ table: name of the table the column belongs to
❑ max_length: maximum length of the column
❑ not_null: 1, if the column cannot be null
❑ primary_key; 1, if the column is a primary key
❑ unique_key: 1, if the column is a unique key
❑ multiple_key: 1, if the column is a non-unique key
❑ numeric: 1, if the column is numeric
❑ blob: 1, if the column is a BLOB
❑ type: the type of the column
❑ unsigned: 1, if the column is unsigned
❑ zerofill: 1, if the column is zero-filled
Example
SELECT employee.name, department.deptname Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 18If mysql_fetch_field()is called on the result identifier containing the result of the above query, then the first call will return the description of employee.name field, and the second call will return the description of department.deptname field
mysql_field_seek
The function sets the fetch_field offset of the result_identifier to field_offset
int mysql_field_seek(int result_identifier, int field_offset);
result_identifie
mysql_db_query, mysql_query, mysql_list_tables,
mysql_list_dbs
field_offset The index for the field in the result
identifier The field_offset and result_identifier parameters are both required The next call to mysql_fetch_field() will return the object describing the field_offset, field of the result identifier
The function returns true on success, else false on failure
mysql_fetch_object
Returns an object that corresponds to the fetched row from the result identifier
object mysql_fetch_object(int result_identifier, int [result_type]);
result_identifie
r
The result identifier returned by mysql_db_query, mysql_query, mysql_list_tables,
Trang 19The function is similar to mysql_fetch_array, except that an object is returned, instead of an array Therefore only MYSQL_ASSOC or MYSQL_BOTH will make sense, because numbers cannot be names for object properties Therefore, if you need to access fields with the same name in different tables, you will need to alias them If you used the SELECT query:
SELECT tab1.id AS id1, tab2.id AS id2 ( )
Then you can access the results by using:
$result = mysql_query("SELECT ( )"); $row = mysql_fetch_object($result);
And then referring to $row->id1 and $row->id2 will return the corresponding result field
echo $row->deptname;
} mysql_free_result($result);
?>
In the above example, the columns of the rows are accessed by field names
mysql_fetch_array
Fetches the row as an associative array
array mysql_fetch_array(int result_identifier, int [result_type]);
result_identifie
mysql_db_query, mysql_query, mysql_list_tables,
mysql_list_dbs
result_type A constant indicating what type (or types)
of array to return
MYSQL_BOTH
The result_identifier parameter is required The second optional argument result_type
can have the following values
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 20❑ MYSQL_NUM: Will cause the returned array to contain numeric indices only (similar to mysql_fetch_row())
❑ MYSQL_ASSOC: Will cause the returned array to contain associative indices only
❑ MYSQL_BOTH: Will cause the returned array to contain both numeric and associative indices
If the second argument result_type is not specified, then MYSQL_BOTH is assumed as the value for the second argument
Each subsequent call of mysql_fetch_array() will return an array corresponding to the next row, or false if there are no more rows
This is an extended version of mysql_fetch_row(), which returns only a numerically indexed array By contrast mysql_fetch_array() returns the results also as an associative array using the field names as keys, this without incurring any performance penalties The limitation of the
associative array is that if there is duplication in the field names, the last one will take precedence and you will need to use the numerical index to extract the other fields with the same name, or use aliasing
of the result fields For example, if the SQL query was:
SELECT tab1.id, tab2.id ( ) FROM tab1,tab2 ( )
And you used:
$result = mysql_query("SELECT ( )");
$row = mysql_fetch_array($result);
Then, referring to $row["id"] will return the contents of tab2.id To access tab1.id, we can use $row[0] Alternatively, if your SQL query was:
SELECT tab1.id as id1, tab2.id as id2 ( )
Then you will be able to refer to $row["id1"] and $row["id2"] to access the corresponding field
Example
<?php
$stmt = "SELECT employee.name, department.deptname
FROM employee , department
WHERE emplyee.deptno = department.deptno";
Trang 21mysql_fetch_lengths
Retrieves the lengths of each field in the last fetched row
array mysql_fetch_lengths(int result_identifier);
The function returns an array that corresponds to the lengths of each field in the last row fetched by mysql_fetch_row(), or false on error
mysql_result
Get the data from the result identifier
mixed mysql_result(int result_identifier, int row, mixed [field]);
result_identifie
mysql_db_query, mysql_query, mysql_list_tables,
mysql_list_dbs
row The row from which to retrieve the data
field The field in the row from which to
retrieve the data
The next field in the row
The result_identifier and row parameters are required, though field is optional The function returns the contents of the row row and column field from the result_identifier The optional argument field can be column offset, column name or table.column_name If the field argument is not specified then the next field of the row is returned
mysql_free_result
The function frees the memory associated with the result identifier
int mysql_free_result(int result_identifier);
result_identifie
mysql_db_query, mysql_query, mysql_list_tables,
mysql_list_dbs
The result_identifier parameter is required The function is used only if you estimate that your script is using too much memory when running Calling this function on a result handler will free all associated data in memory
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 22mysql_errno
Returns the error number of the previous MySQL operation
int mysql_errno(int [link_identifier]);
link_identifier The reference for the connection on
which the previous request was sent to the Database Server
The link identifier for the last connection opened
The link_identifier parameter is optional mysql_errno() should be used to get the error numbers generated by the MySQL server
See the MySQL mysqld_error.h file for the list of error numbers and their
descriptions
mysql_error
Returns the error message for the previous MySQL operation
string mysql_error(int [link_identifier]);
link_identifier The reference for the connection on
which the previous request was sent to the Database Server
The link identifier for the last connection opened
The link_identifier parameter is optional mysql_error() should be used to get the error messages generated by the MySQL server Errors from the MySQL server do not cause halting of the script being processed
A Sample PHP-MySQL Application
Any PHP script accessing a MySQL database does the following:
1 Connect to the MySQL Database Server
2 Send the SQL query to the MySQL Database Server, and get the result
3 Use the set of API’s to get the data from the result that is returned in Step 2
4 Generate the HTML page, for displaying the contents
Let’s implement a sample web-based address book application The address book application allows users to create a new entry in the address book, delete an existing entry, modify an entry and search
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 23for entries The application uses MySQL for storing the addresses, and uses PHP for displaying the content in HTML format
The address book entries are stored in “addressbook” table The “addressbook” table can be created in the MySQL database by executing the following SQL command
CREATE addressbook ( NAME VARCHAR (255), CITY VARCHAR(255), DESCRIPTION VARCHAR(255), TELEPHONE VARCHAR(255), ROWID INT PRIMARY KEY AUTO_INCREMENT) ) ;
Each row in the addressbook table is uniquely identified by the ROWID field
Before looking at the code of the application, lets first look at a few screenshots to get a feel of the application
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 24This is the main page of the application From here, users can add new entries in the address book or search the address book, by clicking the appropriate button
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 25The search page, shown above, is returned when the user clicks on the Search Address Book button
on the main page Here the user specifies the search criteria The search functionality is quite simple,
it does not support wildcard characters like ‘*’, ‘?’ etc For the above search criteria, all the entries in the address book which contain the sub string ‘ha’ in the name attribute and sub string ‘ban’ in the
city attribute are returned
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 26This page contains the search results for the search criteria mentioned earlier From here the user can modify the attributes or delete the entries
For modifying the attributes the user, clicks on the Modify link corresponding to the entry This will
return the modify page, where the user can specify the new attributes for the entry For deleting an
entry the user clicks on the Delete link corresponding to the entry
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 27This page, allows the user to specify new attributes for an entry Having modified these attributes, the
user clicks on the Modify button
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 28This page is returned, after the user clicks on the Add a New Entry button on the main page User
enters the values for the attributes and clicks on the Add Entry button to create a new entry The Name and e-mail fields are mandatory fields
Now that we have looked at the screenshots of the application, and have a broad understanding of what it is meant to do, let’s look at the complete code of the application
Trang 29$hostName="www.harawat.com" ; // Machine on which MySQL Database is running
All the PHP scripts connect to the MySQL database as user ‘php’
$userName="php" ; // Database User Login
$password="php" ; // Database User Password
$databaseName = "php" ; // Database name
Name of the table, in which addressbook is stored
$tableName = "addressbook" ; // Name of the table
GenerateHTMLHeader() function is used to generate HTML header for all the pages of the application
// Generate the HTML header function GenerateHTMLHeader($message) {
printf("<HEAD> <TITLE> Address Book on the Web </TITLE> </HEAD>");
printf("<BODY TEXT=\"#000000\" BGCOLOR=\"#999999\" LINK=\"#0000EE\"
VLINK=\"#551A8B\" ALINK=\"#FF0000\">\n");
printf("<H1><FONT SIZE=+4>My Address Book</FONT></H1><BR><BR>");
printf("<TABLE CELLPADDING=4 CELLSPACING=0 BORDER=0 WIDTH=600>");
printf("<TR BGCOLOR=\"#DCDCDC\"><TD><FONT FACE=Arial><B>");
GenerateFrontPage() function generates the main page of the application
// Generates the main page function GenerateFrontPage() {
Generate a HTML form with action script as main.php
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 30Generate a button with value “Search Address Book”
printf("<INPUT TYPE=\"submit\" NAME=\"choice\" VALUE=\"Search Address Book\">"); printf(" ");
Generate a button with value “Add a New entry”
printf("<INPUT TYPE=\"submit\" NAME=\"choice\" VALUE=\"Add a New Entry\">"); printf("<BR>");
printf("<BR>");
Print the instructions on how to use the application:
printf("<UL>");
printf("<LI> Search entries in the Address Book by clicking on
<I>Search Address Book</I> button</LI>");
printf("<LI> Add entries to the Address Book by clicking on
<I>Add a new Entry</I> button </LI>");
printf("<LI> Modify an existing entry by clicking <I>Search Address Book</I> button first and then choosing the entry to Modify</LI>");
printf("<LI> Delete an existing entry by clicking <I>Search Address Book</I> button first and then choosing the entry to Delete</LI>");
printf("</UL>") ;
printf("</FORM>");
}
DisplayErrMsg() function displays the error message $message This function is used
throughout the code for displaying error messages
// Display error messages
function DisplayErrMsg( $message ) {
// Generate the HTML form for add/modify/search
function GenerateHTMLForm($formValues, $actionScript, $submitLabel) {
Generate a HTML form
printf("<FORM METHOD=post ACTION=\"%s\"><PRE>\n", $actionScript);
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 31Display the attributes of the entry in text boxes The text boxes will contain the existing values of the attributes (as in the case of modify), or will be empty (as in the case of search and add)
Generate a button with value $submitLabel
printf("<INPUT TYPE=submit VALUE=\"%s\">", $submitLabel );
Generate an HTML form with main.php as action script
printf("<BR><FORM ACTION=\"main.php\" METHOD=post>\n");
Create a submit button with value “Click”
printf("<INPUT TYPE=submit VALUE=\"Click\"> to return to Main Page\n");
}
main.php
The script main.php, generates the main page of the application This script also is executed, after the
user clicks on the Add a New Entry or Search Address Book button on the main page of the
application
<?php Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 32require("common.php") ;
If the value of the form variable $choice is null, then generate the main page of the application:
// Check if the page is called for the first time
if (!$choice){
Generate the header of the main page:
GenerateHTMLHeader("Click below to access the Address Book");
Generate the main page
GenerateFrontPage();
If the value of the form variable $choice is “Search Address Book”, then generate an HTML form with which the user can specify the search criteria
} else if ($choice == "Search Address Book"){
GenerateHTMLHeader( "Search using the following criteria:" );
Generate an HTML form, containing a submit button with value “SEARCH” and action script set as search.php
GenerateHTMLForm( 0, "search.php", "SEARCH" );
}
If the value of the form variable $choice is “Add a New Entry”, then generate an HTML form with which the user can enter the attributes of the new entry
else if ($choice == "Add a New Entry"){
GenerateHTMLHeader( "Please fill in fields: (Name and E-mail mandatory)" );
Generate an HTML form, consisting of a submit button with value “ADD ENTRY” and action script set as add.php
GenerateHTMLForm(0, "add.php", "ADD ENTRY ") ;
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 33<?
//add.php
require("globals.php") ; require("common.php") ;
$addStmt holds a SQL statement template for inserting the row corresponding to the new entry in the database table
$addStmt = "Insert into $tableName(NAME, EMAIL, CITY, DESCRIPTION, TELEPHONE) values('%s', '%s', '%s', '%s', '%s')" ;
Verify that the user enters the mandatory attributes:
// Check if all the variables are entered
if (!$cn || !$mail ) { DisplayErrMsg(" Error: All the fields are mandatory") ; exit() ;
}
Open a persistent connection with the database server Remember that the variables $hostName,
$userName, $password are defined in globals.php file
// Connect to the Database
if (!($link=mysql_pconnect($hostName, $userName, $password))) { DisplayErrMsg(sprintf("error connecting to host %s, by user %s", $hostName, $userName)) ;
exit() ; }
Select the database $databaseName The variable $databaseName is also defined in globals.php
// Select the Database
if (!mysql_select_db($databaseName, $link)) { DisplayErrMsg(sprintf("Error in selecting %s database", $databaseName)) ; DisplayErrMsg(sprintf("error:%d %s", mysql_errno($link), mysql_error($link)))
; exit() ; }
Send the SQL statement to the Database Server for execution
// Execute the Statement
if (!mysql_query(sprintf($addStmt,$cn, $mail, $locality, $description,
$telephonenumber), $link)) { DisplayErrMsg(sprintf("Error in executing %s stmt", $stmt)) ; DisplayErrMsg(sprintf("error:%d %s", mysql_errno($link), mysql_error($link))) Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 34}
Generate the HTML header to display the status of the add operation
GenerateHTMLHeader("The entry was added succesfully");
Generate a footer, to take the user to the main page of the application
Verify if the search criteria is specified
// Check if at least one search criteria is entered
if (!$cn && !$mail && !$locality && !$description && !$telephonenumber) {
DisplayErrMsg(" Error: At least one search criteria should be present\n") ; exit() ;
}
Generate a SQL SELECT statement corresponding to the search criteria specified by the user:
// Generate the SQL command for doing a select from the Database
$searchStmt = "SELECT * from tableName where " ;
$searchStmt = "telephone '$telephonenumber' and " ;
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 35$stmt= substr($searchStmt, 0, strlen($searchStmt)-4) ;
Open a persistent connection with the Database Server
// Connect to the Database
if (!($link=mysql_pconnect($hostName, $userName, $password))) { DisplayErrMsg(sprintf("error connecting to host %s, by user %s", $hostName, $userName)) ;
exit() ; }
Select the database $databaseName
// Select the Database
if (!mysql_select_db($databaseName, $link)) { DisplayErrMsg(sprintf("Error in selecting %s database", $databaseName)) ; DisplayErrMsg(sprintf("error:%d %s", mysql_errno($link), mysql_error($link)))
; exit() ; }
Send the SQL command to the database server for execution
// Execute the Statement
if (!($result =mysql_query($stmt, $link))) { DisplayErrMsg(sprintf("Error in executing %s stmt", $stmt)) ; DisplayErrMsg(sprintf("error:%d %s", mysql_errno($link), mysql_error($link)))
; exit() ; }
Display the results of the SELECT query
// Display the results of the search
Each row in the result of the SQL query is displayed in a separate row of the table
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 36while (($row = mysql_fetch_object($result))){
The last column of the row contains links for deleting the entry
(HREF=\"delete.php?rowid=%s\") or modifying (HREF=\"modify.php?rowid=%s\") the attributes of the entry Each entry is uniquely identified by the ROWID attribute Notice that
modify.php and delete.php are called with rowid variable containing the ROWID attribute of the entry
<?
// modify.php
require("globals.php") ;
require("common.php") ;
SQL statement to get the current values of the entry:
$selectStmt = "SELECT * FROM $tableName WHERE ROWID=$rowid" ;
Open a persistent connection with the Database Server:
// Connect to the Database
if (!($link=mysql_pconnect($hostName, $userName, $password))) {
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 37DisplayErrMsg(sprintf("error connecting to host %s, by user %s", $hostName, $userName)) ;
exit() ; }
Select the database $databaseName:
// Select the Database
if (!mysql_select_db($databaseName, $link)) { DisplayErrMsg(sprintf("Error in selecting %s database", $databaseName)) ; DisplayErrMsg(sprintf("error:%d %s", mysql_errno($link), mysql_error($link)))
; exit() ; }
Send the SQL statement to the database server for execution:
// Execute the Statement
if (!($result= mysql_query($selectStmt, $link))) { DisplayErrMsg(sprintf("Error in executing %s stmt", $selectStmt)) ; DisplayErrMsg(sprintf("error:%d %s", mysql_errno($link), mysql_error($link)))
; exit() ; }
Generate the HTML header with message “Please modify fields”:
GenerateHTMLHeader( "Please modify fields") ;
Fetch the row from the $result variable:
GenerateHTMLForm( $resultEntry, "update.php?rowid=$rowid", "MODIFY" );
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 38mysql_free_result($result) ;
?>
update.php
The script update.php, updates the attributes of an entry in the database table It gets called, when
the user, after entering the new attributes of the entry, clicks on the MODIFY button on the Modify
page The script is called with form variables $cn, $mail, $locality, $description and
$telephonenumber containing the new attributes of the entry The form variable $rowid contains the value of ROWID attribute of the entry, and it uniquely identifies the entry
<?
// update.php
require("globals.php") ;
require("common.php") ;
SQL statement for updating the attributes of the entry:
$updateStmt = "Update $tableName set NAME='$cn', EMAIL='$mail',
CITY='$locality', DESCRIPTION='$description', TELEPHONE='$telephonenumber' WHERE ROWID=$rowid" ;
Open a persistent connection with the Database Server:
// Connect to the Database
if (!($link=mysql_pconnect($hostName, $userName, $password))) {
DisplayErrMsg(sprintf("error connecting to host %s, by user %s",
$hostName, $userName)) ;
exit() ;
}
Select the database $databaseName:
// Select the Database
Send the SQL statement to the database server for execution:
// Execute the Statement
if (!mysql_query($updateStmt, $link)) {
DisplayErrMsg(sprintf("Error in executing %s stmt", $updateStmt)) ;
DisplayErrMsg(sprintf("error:%d %s", mysql_errno($link), mysql_error($link)))
;
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 39exit() ; }
Display the operation successful message
GenerateHTMLHeader("The entry was modified succesfully");
Display the footer, to take the user to the main page of the application
<?
// delete.php
require("common.php") ; require("globals.php") ;
SQL statement for deleting the entry from the database table:
$deleteStmt = "DELETE from $tableName where ROWID=$rowid" ;
Open a persistent connection with the database server:
// Connect to the Database
if (!($link=mysql_pconnect($hostName, $userName, $password))) { DisplayErrMsg(sprintf("error connecting to host %s, by user %s", $hostName, $userName)) ;
exit() ; }
Select the database $databaseName:
// Select the Database
if (!mysql_select_db($databaseName, $link)) { DisplayErrMsg(sprintf("Error in selecting %s database", $databaseName)) ; DisplayErrMsg(sprintf("error:%d %s", mysql_errno($link), mysql_error($link))); exit() ;
}
Send the SQL statement to the database server for execution
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com
Trang 40// Execute the Statement
if (!mysql_query($deleteStmt, $link)) {
DisplayErrMsg(sprintf("Error in executing %s stmt", $deleteStmt)) ;
DisplayErrMsg(sprintf("error:%d %s", mysql_errno($link), mysql_error($link))); exit() ;
}
Generate the HTML header to display the status of delete operation
// Add the code to show the success
GenerateHTMLHeader("The entry was deleted succesfully");
Generate a footer, to take the user to the main page of the application
Here is what we covered in this chapter
❑ A basic introduction to databases;
❑ Basic SQL commands, including data definition and data manipulation statements;
❑ Features of the MySQL database;
❑ PHP API’s for accessing MySQL database;
❑ A sample database web application
Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com