Tải bản đầy đủ (.pdf) (86 trang)

Professional PHP Programming phần 4 ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.93 MB, 86 trang )

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 -
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 -
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 -
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 -
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 -

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 -

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 -
$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 -
// 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 -
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 -
statement).

int mysql_num_rows(int result_identifier);

Parameter Description Default
result_identifie
r
The result identifier returned by
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);

Parameter Description Default
result_identifie
r
The result identifier returned by
mysql_list_tables,
mysql_list_dbs

i
The index in the
result_identifier


Both the result_identifier and i parameters are required. The function returns the
table/database name at index i in the result identifier.

mysql_num_rows() can be used to find the number of table/database names in the result identifier.

For example, to get the list of all the databases in the MySQL server:

<HTML>
<HEAD>
<TITLE> List of Databases </TITLE>
</HEAD>

<BODY>

<?php
$userName="php";
$password="php";
$hostName="www.harawat.com";

Open a connection with the Database Server.

// Connect to the MySQL Database
























































TEAM FLY PRESENTS
Simpo PDF Merge and Split Unregistered Version -
if (!($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));
$noOfDbs++;
}
// Free the result pointer

mysql_free_result($listOfDbs);

?>

</BODY>
</HTML>
mysql_list_fields
Retrieves the information about a table.

int mysql_list_fields(string database_name, string table_name, int
[link_identifier]);

Parameter Description Default
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
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























































TEAM FLY PRESENTS
Simpo PDF Merge and Split Unregistered Version -
connection 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);

Parameter Description Default
result_identifie
r
The result identifier returned by
mysql_db_query, mysql_query,
mysql_list_tables,
mysql_list_dbs


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


Parameter Description Default
result_identifie
r
The result identifier returned by
mysql_db_query, mysql_query,
mysql_list_tables,
mysql_list_dbs

field_offset
The index for the field in the result
identifier


The result_identifier and field_offset parameters are required. The function returns the
length of the field, at field_offset in the result_identifier.
























































TEAM FLY PRESENTS
Simpo PDF Merge and Split Unregistered Version -
mysql_field_name
Retrieves the name of a field in the database.

string mysql_field_name(int result_identifier, int field_index);

Parameter Description Default
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 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);

Parameter Description Default
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
type of the field at offset field_index in the result_identifier.
mysql_field_flags
Retrieves the flags for a given field.

string mysql_field_flags(int result_identifier, int field_index);

Parameter Description Default
result_identifie
r

The result identifier returned by
mysql_db_query, mysql_query,
mysql_list_tables,
mysql_list_dbs
























































TEAM FLY PRESENTS

Simpo PDF Merge and Split Unregistered Version -
field_index
The index for the field in the result
identifier


The result_identifier and field_index parameters are required. The function returns the
flags (such as not null, primary key) associated with the field at offset field_index in the
result_identifier.
mysql_field_table
Retrieves the name of the table to which a specific field belongs.

string mysql_field_table(int result_identifier, int field_index);

Parameter Description Default
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] );

Parameter Description Default
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
This function, whose parameter is optional, Retrieves the auto-increment id generated by the last
























































TEAM FLY PRESENTS
Simpo PDF Merge and Split Unregistered Version -
executed INSERT SQL command on a table that contained an AUTO_INCREMENT column.

int mysql_insert_id(int [link_identifier]);

Parameter Description Default
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);

Parameter Description Default
result_identifie
r
The result identifier returned by
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);

Parameter Description Default
result_identifie
r
The result identifier returned by

mysql_db_query, mysql_query,
mysql_list_tables,
mysql_list_dbs

row_number
The index of the row to which to set the
pointer.


The result_identifier and row_number parameters are both required. The function sets the
internal row pointer of the result_identifier to row_number. The next call to
mysql_fetch_row will return row_number row.

























































TEAM FLY PRESENTS
Simpo PDF Merge and Split Unregistered Version -
The 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]);

Parameter Description Default
result_identifie
r
The result identifier returned by
mysql_db_query, mysql_query,
mysql_list_tables,
mysql_list_dbs

field_offset
The index for the field in the result
identifier
The next field not
retrieved with
mysql_fetch_f
ield


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
FROM employee, department
WHERE emplyee.deptno = department.deptno
























































TEAM FLY PRESENTS
Simpo PDF Merge and Split Unregistered Version -

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

Parameter Description Default

result_identifie
r
The result identifier returned by
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]);

Parameter Description Default
result_identifie
r
The result identifier returned by
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_ASSOC

The result_identifier parameter is required. The optional argument result_type can have
the following values (similar to mysql_fetch_array):

❑ MYSQL_NUM
❑ MYSQL_ASSOC
❑ MYSQL_BOTH
























































TEAM FLY PRESENTS
Simpo PDF Merge and Split Unregistered Version -

The 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.
Example
<?php
$stmt = "SELECT employee.name, department.deptname FROM employee, department
WHERE emplyee.deptno = department.deptno";

mysql_connect($host,$user,$password);
$result = mysql_db_query("php",$stmt);
while($row = mysql_fetch_object($result)) {
echo $row->name;
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]);

Parameter Description Default
result_identifie
r
The result identifier returned by
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

























































TEAM FLY PRESENTS
Simpo PDF Merge and Split Unregistered Version -
❑ 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";


mysql_connect($host,$user,$password);
$result = mysql_db_query("php",$stmt) ;
while($row = mysql_fetch_object($result), MYSQL_ASSOC) {
echo $row["name"];
echo $row["deptname"];
}
mysql_free_result($result);
?>
























































TEAM FLY PRESENTS
Simpo PDF Merge and Split Unregistered Version -
mysql_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]);

Parameter Description Default
result_identifie
r
The result identifier returned by
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);

Parameter Description Default
result_identifie
r
The result identifier returned by
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.
























































TEAM FLY PRESENTS
Simpo PDF Merge and Split Unregistered Version -
mysql_errno
Returns the error number of the previous MySQL operation.

int mysql_errno(int [link_identifier]);

Parameter Description Default
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]);

Parameter Description Default
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























































TEAM FLY PRESENTS

Simpo PDF Merge and Split Unregistered Version -
for 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.

























































TEAM FLY PRESENTS
Simpo PDF Merge and Split Unregistered Version -


This 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.

























































TEAM FLY PRESENTS
Simpo PDF Merge and Split Unregistered Version -


The 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.

























































TEAM FLY PRESENTS
Simpo PDF Merge and Split Unregistered Version -

×