Chap 5 Web Extension
Chap 5 Web Extension
XML
What is XML?
XML is a meta-language, which can be used to store data & act as a mechanism to transfer
information between dissimilar systems.
XML stands for EXtensible Markup Language.
XML is a markup language much like HTML.
XML was designed to describe data.
XML tags are not predefined in XML. You must define your own tags.
XML is self describing.
XML uses a DTD (Document Type Definition) to formally describe the data.
<?xml version=”1.0”?>
<Person>
<Firstname>Ralph</Firstname>
<Lastname>Mosely</Lastname>
</Person>
Use of XML
Used to exchange data between dissimilar systems.
Used to describe content of document.
XML can be used as database to store data.
Features of XML
XML has its own tag so it’s self describing.
Language Independent:Any language is able to read & write XML.
OS Independent: can be work on any platform.
Readability: It’s a plain text file in user readable format so you can edit or viewin simple editor.
1
5 – Web Extension: PHP and XML
Hierarchical: It has hierarchical structure which is powerful to express complex data and simple to
understand.
<bookstore>
<book category="CHILDREN">
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
<file type="gif">computer.gif</file>
1
5 – Web Extension: PHP and XML
4.) XML Namespace
o The XML namespace is a special type of reserved XML attribute that you place in an XML tag.
o The reserved attribute is actually more like a prefix that you attach to any namespace you
create.
o This attribute prefix is "xmlns:” which stands for XML Namespace.
o The colon is used to separate the prefix from your namespace that you are creating.
o xmlns must have a unique value that no other namespace in the document has. What is
commonly used is the URI (Uniform Resource Identifier) or the more commonly used URL.
Xmlns=”http://www.mydomian.com/ns/animals/1.1”
1
5 – Web Extension: PHP and XML
<?xml version="1.0"?>
<!DOCTYPE note [
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
<note>
<to>Ravi</to>
<from>Ketan</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "note.dtd">
<note>
<to>Ravi</to>
<from>Narendra</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
o This is a copy of the file "note.dtd" containing the Document Type Definition:
1
5 – Web Extension: PHP and XML
<?xml version="1.0"?>
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
DTD - Elements
In the DTD, XML elements are declared with an element declaration. An element declaration has the
following syntax:
Empty elements
o Empty elements are declared with the keyword EMPTY inside the parentheses:
o #CDATA means the element contains character data that is not supposed to be parsed bya
parser.
o #PCDATA means that the element contains data that IS going to be parsed by a parser.
o The keyword ANY declares an element with any content.
o If a #PCDATA section contains elements, these elements must also be declared.
Elements with children (sequences)
o Elements with one or more children are defined with the name of the children
elementsinside the parentheses:
1
5 – Web Extension: PHP and XML
o When children are declared in a sequence separated by commas, the children must appearin
the same sequence in the document. In a full declaration, the children must also bedeclared,
and the children can also have children. The full declaration of the notedocument will be:
Wrapping
o If the DTD is to be included in your XML source file, it should be wrapped in aDOCTYPE
definition with the following syntax:
1
5 – Web Extension: PHP and XML
o The example declaration above declares that the child element message can only occurone
time inside the note element.
Declaring minimum one occurrence of the same element
o The * sign in the example above declares that the child element message can occur zeroor
more times inside the note element.
Declaring zero or one occurrences of the same element
o The? Sign in the example above declares that the child element message can occur zeroor
one times inside the note element.
DTD – Attributes
Attributes provide extra information about elements.
Attributes are placed inside the start tag of an element.
Declaring Attributes
o In the DTD, XML element attributes are declared with an ATTLIST declaration. Anattribute
declaration has the following syntax:
o As you can see from the syntax above, the ATTLIST declaration defines the elementwhich
can have the attribute, the name of the attribute, the type of the attribute, and thedefault
attribute value.
o The attribute-type can have the following values:
1
5 – Web Extension: PHP and XML
Value Explanation
CDATA The value is character data
(eval|eval|..) The value must be an enumerated value
ID The value is an unique id
IDREF The value is the id of another element
IDREFS The value is a list of other ids
NMTOKEN The value is a valid XML name
NMTOKENS The value is a list of valid XML names
ENTITY The value is an entity
ENTITIES The value is a list of entities
NOTATION The value is a name of a notation
xml: The value is predefined
DTD example:
<!ELEMENT square EMPTY>
<!ATTLIST square width CDATA "0">
XML example:
<square width="100"></square>
o In the above example the element square is defined to be an empty element with
theattributes width of type CDATA. The width attribute has a default value of 0.
XML Schema
An XML Schema describes the structure of an XML document.
XML Schema is an XML-based alternative to DTD.
The XML Schema language is also referred to as XML Schema Definition (XSD).
XML Schema is a W3C Recommendation.
XSD Elements
XML Schemas define the elements of your XML files. It’s of two types:
o Simple
o Complex Type
1
5 – Web Extension: PHP and XML
XSD Simple Elements
A simple element is an XML element that can contain only text. It cannot contain any other elements
or attributes.
Defining a Simple Element
o The syntax for defining a simple element is:
<lastname>Refsnes</lastname>
<age>36</age>
<dateborn>1970-03-27</dateborn>
<product pid="1345"/>
o A complex XML element, "employee", which contains only other elements:
1
5 – Web Extension: PHP and XML
<employee>
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>
<description>
It happened on <date lang="norwegian">03.03.99</date> ....
</description>
XSD Attributes
Simple elements cannot have attributes. If an element has attributes, it is considered to be of a
complex type. But the attribute itself is always declared as a simple type.
How to Define an Attribute?
o The syntax for defining an attribute is:
XSL
What is XSL?
XSL stands for EXtensible Stylesheet Language.
XSL = Style Sheets for XML
XSL describes how the XML document should be displayed!
XSL - More Than a Style Sheet Language
XSL consists of three parts:
o XSLT-a language for transforming XML documents
o XPath-a language for navigating in XML documents
o XSL-FO-a language for formatting XML documents
What is XSLT?
XSLT stands for XSL Transformations.
XSLT is the most important part of XSL.
XSLT transforms an XML document into another XML document.
XSLT uses XPath to navigate in XML documents.
Linking
The style sheet is linked into the XML by adding the connecting statement to the XML document:
<?xml-stylesheet type=”text/xsl” href=”libstyle.xsl” ?>
XSL Transformations
XSLT is the most important part of XSL.
XSLT is used to transform an XML document into another XML document, or another type of
document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by
transforming each XML element into an (X)HTML element.
With XSLT you can add/remove elements and attributes to or from the output file. You can also
11
5 – Web Extension: PHP and XML
rearrange and sort elements, perform tests and make decisions about which elements to hide and
display, and a lot more.
A common way to describe the transformation process is to say that XSLT transforms an XML
source-tree in to an XML result-tree.
XSLT Uses XPath:
o XSLT uses XPath to find information in an XML document.
o XPath is used to navigate through elements and attributes in XML documents.
XSLT Works as:
o In the transformation process, XSLT uses XPath to define parts of the source document
that should match one or more predefined templates.
o When a match Is found, XSLT will transform the matching part of the source document
into the result document.
XSL Elements
XSL contains many elements that can be used to manipulate, iterate and select XML, for output.
o value-of
o for-each
o sort
o if
o choose
<xsl:value•of> Element
The <xsl:value-of> element extracts the value of a selected node.
The <xsl:value-of> element can be used to select the value of an XML element and add it to the
output.
Syntax
<xsl:value-of select="expression" />
o expression: This is Required. An XPath expression that specifies which node/attribute to
extract the value from. It works like navigating a file system where a forward slash (/) selects
subdirectories.
<xsl:for•each> Element
The XSL <xsl:for-each> element can be used to select every XML element of a specified node-set.
<xsl:if> Element
To put a conditional if test against the content of the XML file, add an <xsl:if> element to the XSL
document.
Syntax
<xsl:if test="expression">
...some output if the expression is
true...
</xsl:if>
<xsl:sort> Element
The <xsl:sort> element is used to sort the output.
<xsl:sort select="artist"/>
The select attribute indicates what XML element to sort on.
11
5 – Web Extension: PHP and XML
Example using value•of, for•each and if
</td>
<td><
xsl:value-of select="artist"/>
</td>
</tr>
</xsl:if>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
<xsl:choose> Element
The <xsl:choose> element is used in conjunction with <xsl:when> and <xsl:otherwise> to express
multiple conditional tests.
11
5 – Web Extension: PHP and XML
Syntax
<xsl:choose>
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>
<xsl:apply-templates> Element
The <xsl:apply-templates> element applies a template to the current element or to the current
element's child nodes.
If we add a select attribute to the <xsl:apply-templates> element it will process only the child
element that matches the value of the attribute. We can use the select attribute to specify the order
in which the child nodes are processed.
Look at the following XSL style sheet:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="cd">
<p>
<xsl:apply-templates select="title"/>
<xsl:apply-templates select="artist"/>
</p>
</xsl:template>
</xsl:stylesheet>
11
5 – Web Extension: PHP and XML
sheet available!
The answer to this process the document and style sheet outside of the browser’s own mechanism
for doing this task.
This task can be done either on the client side or the server side.
Using JavaScript
One way to process and transform XML on the client side is using JavaScript, which has several
features for doing the task very well.
<html>
<body>
<script type=”text/javascript”>
//Load the XML document
var xml= new ActiveXObject(“Microsoft.XMLDOM”)
xml.async=false
xml.load(“lib.xml”)
//Load the XSL document
var xsl= new ActiveXObject(“Microsoft.XMLDOM”)
xsl.async= false
xsl.load(“libstyle.xsl”)
//Do the actual transform
document.write(xml.transformNode(xsl))
</script>
</body>
</html>
Above example shows one way to transform with JavaScript using Microsoft’s proprietary
Application Programming Interface (API) for the Internet Explorer browser.
It is also possible to process XML using the DOM.
Using both the of these mechanisms it is possible to also traverse an XML document and process
either according to a style sheet or simply using the JavaScript to make the stylistic decisions.
Apart from JavaScript, it is also possible to use other programming languages (such as Java and .Net)
to process and then output a transformed document.
11
5 – Web Extension: PHP and XML
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to
produce dynamic websites.
PHP scripts execute on web server and serve WebPages to user on request.
PHP was originally created by RasmusLerdorf in 1994. Programmer RasmusLerdorf initially created a
set of C scripts he called "Personal Home Page Tools" to maintain his personal homepage. The scripts
performed tasks such as displaying his résumé and recording his web-page traffic.
These were released and extended to include a package called the Form Interpreter (PHP/FI). While
PHP originally stood for "Personal Home Page", it is now said to stand for "PHP: Hypertext
Preprocessor", a recursive acronym.
PHP code is embedded into the HTML source document and interpreted by a web server with a PHP
processor module, which generates the web page document. It also has evolved to include a
command-line interface capability and can be used in standalone graphical applications.PHP can be
deployed on most web servers and as a standalone interpreter, on almost every operating system
and platform free of charge.
In 1997 ZeevSuraski and AndiGutmans along with Rasmus rewrite PHP and released PHP version 3.0
in June 1998.After this release PHP becomes so much popular.
The PHP version 4.0 was launched in May 2000.This version includes session handling, output
buffering, a richer cire language and support for wide variety of web server platforms.
The PHP 5.0 version released in 2004 with object oriented programming concept.
Web Server
A Web Server is computer and the program installed on it. Web Server interacts with the client
through the browser. It delivers the web pages to the client and to an application by using the web
browser and HTTP protocol respectively.
We can also define the web server as the package of larger number of programs installed on a
computer connected to internet or intranet for downloading the requested files using File Transfer
Protocol, serving e- mail and building and publishing web pages.
10
5 – Web Extension: PHP and XML
A web server works on client server model. A computer connected to internet or intranet must have
a server program.
A computer connected to the internet for providing the services to a small company or a department
store may contain the HTTP server to access and store WebPages and files, SMTP server to support
mail services, FTP server for files downloading and NNTP server for newsgroup.
The computer containing all the above servers is called the web server.
MySQL
MySQL is a relational database management system (RDBMS) that runs as a server providing
multi-user access to a number of databases.
It is named after developer Michael Widenius' daughter, My. The SQL phrase stands for Structured
Query Language.
The data in MySQL is stored in database objects called tables. A table is a collection of related data
entries and it consists of columns and rows.
The MySQL development project has made its source code available under the terms of the License.
The license can require improved versions of the software to carry a different name or version from
the original software.
First released in January,1998, MySQL was owned and sponsored by the Swedish company MySQL
AB, now owned by Oracle Corporation.
MySQL is fully multithreaded using kernel threads, and provides application programming interfaces
(APIs) for many programming languages, including C,C++, Java, Perl, PHP, Python.
MySQL is used in a wide range of applications, including data warehousing, e-commerce, Web
databases, logging applications and distributed applications.
10
5 – Web Extension: PHP and XML
Relationship between Apache, MySQL and PHP (AMP Module)
AMP stands for Apache MySQL PHP
PHP
PHP is a server side scripting that was designed for creating dynamic websites. It slots into your
Apache web server and processes instructions contained in a web page before that page is sent
through to your web browser.
PHP is a powerful scripting language that can be run in the command line of any computer with
PHPinstalled. However, PHP alone isn't enough in order to build dynamic web sites.
Apache
To use PHP on a web site, you need a server that can process PHP scripts. Apache is a free web
Server that, once installed on a computer, allows developers to test PHP scripts locally; this makes it
an invaluable piece of your local development environment.
Like all web servers, Apache accepts an HTTP request and serves an HTTP response.
MySQL
Additionally, dynamic websites are dependent on stored information that can be modified quickly
and easily; this is the main difference between a dynamic site and a static HTML site. However, PHP
doesn’t provide a simple, efficient way to store data. This is where a relational database
management system like MySQL comes into play. PHP provides native support for it and the
database is free, open-source project.
MySQL is a relational database management system (DBMS). Essentially, this means that MySQL
allows users to store information in a table-based structure, using rows and columns to organize
different pieces of data.
Numeric Array
Associative Array
Multidimensional Array
Numeric Array
In numeric array each element having numeric key associated with it that is starting from 0;
You can use array() function to create array.
The general syntax is given below:
$array_name=array ( value1, value2 …valueN);
For Example:
10
5 – Web Extension: PHP and XML
<?php $myarray=array(‘A’,’B’,’C’);
print_r($myarray);
?>
You can refer to individual element of an array in PHP script using its key value as shown below:
<?php
$myarray=array(‘A’,’B’,’C’);
echo $myarray[1];
?>
It will display
B
In Numeric Array you can use for, while or do while loop to iterate through each element in array
because in numeric array key values are consecutive.
<?php
$myarray=array(“Apache”, “MySQL”, “PHP”);
for($i=0;$i<3;$i++)
{
echo $myarray*$i+.”<br>”;
}
?>
Output:
Apache
MySQL
PHP
Associative Array
The associative part means that arrays store element values in association with key values rather
than in a strict linear index order.
If you store an element in an array, in association with a key, all you need to retrieve it later from
that array is the key value.
Key may be either numeric or string.
You can use array() function to create associative array.
The general syntax is given below:
$array_name=array(key1=>value1, key1=>value1,….. keyN=>valueN);
10
5 – Web Extension: PHP and XML
For Example 1:
<?php $myarray=array(5=>”Apple”, 10=>”Mango”, 20=>”Grapes”);
print_r($my_array);
?>
Output:
Array([5]=>Apple [10]=>Mango [20]=>Grapes)
Example 2:
<?php
$myarray=array(“Name”=>”James” , “Age”=>25, “Gender”=>”Male” );
print_r($myarray);
?>
Output:
Array([Name]=>James [Age]=>25 [Gender]=>Male)
You can refer to individual element of an array in PHP using its key value.
Example:
<?php $myarray=array(“Name”=>”James” , “Age”=>25, “Gender”=>”Male” );
echo “Name:”.$myarray*‘Name’+;
?>
Output:
Name:James
In associative array you cannot use for, while r do..while loop to iterate through each element in
array because in Associative array key value are not consecutive.
So you have to use foreach loop.
For Example:
<?php $myarray=array(“Name”=>”James” , “Age”=>25, “Gender”=>”Male” );
foreach($myarray as $item)
{
}
?>
Output:
10
5 – Web Extension: PHP and XML
echo $item;
James 25 Male
Multidimensional Array
PHP can easily support multidimensional arrays, with arbitrary numbers of key.And just as in one
dimensional arrays, there is no need to declare out intentions in advance. Assignment can be like:
10
5 – Web Extension: PHP and XML
$multi_array*0+*1+*2+*3+=”Good
numerical index.
The values those are stored in array can themselves be arrays, just as legitimately as they can be string or
numbers.
For example:
The integer key of 0 stores a string, and the key 1 stores an array that ,in turn, has a string in it.
It is simply an array with two values stored in association with keys.Each of them values is an array itself. We
can reference it like this
echo
grapes. And
$kind=”flower”;
$color=”yellow”;
print(“ $basket *$kind+
10
5 – Web Extension: PHP and XML
How do you create session & cookie in PHP? Give difference between
session and cookie with example. OR
What are cookies? Explain the cookies handling in PHP with proper
example.
PHP Sessions
A PHP session variable is used to store information about, or change settings for a user session.
Session variables hold information about one single user, and are available to all pages in one
application.
<?phpsession_start(); ?>
<html>
<body>
</body>
</html>
The code above will register the user's session with the server, allow you to start saving user
information, and assign a UID for that user's session.
10
5 – Web Extension: PHP and XML
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
Output:Pageviews=1
In the example below, we create a simple page-views counter. The isset() function checks if the
"views" variable has already been set. If "views" has been set, we can increment our counter. If
"views" doesn't exist, we create a "views" variable, and set it to 1:
<?php
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "Views=". $_SESSION['views'];
?>
Destroying a Session
If you wish to delete some session data, you can use the unset() or the session_destroy() function.
The unset() function is used to free the specified session variable:
<?php
unset($_SESSION['views']);
?>
You can also completely destroy the session by calling the session_destroy() function:
<?php
session_destroy();
?>
Note:session_destroy() will reset your session and you will lose all your stored session data.
10
5 – Web Extension: PHP and XML
PHP Cookie
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer.
Each time the same computer requests a page with a browser, it will send the cookie too. With PHP,
you can both create and retrieve cookie values.
In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it.
We also specify that the cookie should expire after one hour:
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
.....
Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
You can also set the expiration time of the cookie in another way. It may be easier than using
seconds.
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
<html>
.....
In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).
10
5 – Web Extension: PHP and XML
<?php
// Print a cookie
echo $_COOKIE["user"];
In the following example we use the isset() function to find out if a cookie has been set:
<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
</body>
</html>
10
5 – Web Extension: PHP and XML
<html>
<body>
<form action="welcome.php" method="post"> Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
10
5 – Web Extension: PHP and XML
How can you connect to database in PHP? Show the simple database
operation using PHP with proper example.
Integration of PHP with MySQL
It is possible to execute various commands of MySQL from PHP.PHP provides various built-in
functions which you allows you to use MySQL commands from PHP page. Thus you can integrate
PHP with MySQL.
Following are the various PHP functions that allows you the facility of integrating PHP with MySQL:
mysql_connect()
Before you can access data in a database, you must create a connection to the database.
This function allows you to establish connection of PHP application with MySQL server.
Syntax: mysql_connect(servername,username,password);
servername Indicates the name of MySQL server with which you want to establish
connection.
It is optional .Default value is localhost:3306
UserName Indicates the name of user using which you can logs on to MySQL Server.
Optional. Default value is the name of the user that owns the server process.
Password Indicates password of the user using which you can logs on to MySQL Server.
It is optional. Default is "".
If connection establish successfully with MySQL Server then this function returns TRUE value
otherwise it returns FALSE.
Example
<?php
$conn=mysql_connect(“localhost”,”root”,””);
if($conn)
{
} echo “Connected with MySQL”;
else
{
?>
mysql_select_db()
This function allows you to select database from the list of MySQL server databases.
Syntax: mysql_select_db (DatabaseName, ConnectionName);
DatabaseName Indicates the name of the database that you want to select.
ConnectionName Indicates the name of the variable that is used at the time of establish
connection with MySQL server using mysql_connect() function.
1
5 – Web Extension: PHP and XML
If function successfully executed then it returns TRUE otherwise it returns FALSE.
Example:
<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”);
if($db)
{
echo “Database Selected Successfully ”;
}
else
{
echo “Error in selecting Database.”;
}
?>
mysql_query()
This function allows you to specify and execute the MySQL command on MySQL Server.
Syntax:
mysql_query(Query, ConnectionName);
Example
<?php $conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$cmd=mysql_query(“create table Test(ID integer, Name varchar(20))”);
if($cmd)
{
}
else
{
}
?>
1
5 – Web Extension: PHP and XML
echo “Table created
Successfully ”;
echo “Error in
executing query.”;
mysql_fetch_row()
This function allows you to retrieve a record from the recordset that is returned from executing
the MySQL query.
1
5 – Web Extension: PHP and XML
The record that is returned by this function is in the form of numeric array. Numeric array contains
index and value associated with that index.
If there is no record in the record set then it returns false value.
Syntax:
mysql_fetch_row(VariableName);
VariableName indicates the record set that is returned from executing the MySQL command using
mysql_query() function.
Example:
<?php $conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query,$conn);
$ans=mysql_fetch_row($result);
print_r($ans);
mysql_close($con);
?>
mysql_fetch_array()
This function allows you to retrieve a record from the recordset that is returned from executing
the MySQL query.
The record that is returned by this function is in the form of either numeric array, associative array
or both.
If there is no record in record set then it will returns false value.
Syntax:
mysql_fetch_array(VariableName, ResultArrayType)
VariableName:- indicates the record set that is returned from executing the MySQL command
using mysql_query() function.
ResultArrayType:-indicates the type of array to be returned. It can have one of the following
values:
MYSQL_ASSOC This type of array contains name of the field and the value associated with that
field for current record.
MYSQL_NUM This type of array contains index of the field and the value associcated with that
index for current record.
MYSQL_BOTH It is combination of both Associative array and Numeric array. It is the default
type to be returned by this function.
1
5 – Web Extension: PHP and XML
Example:
<?php $conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query, $conn);
$ans=mysql_fetch_array($result,MYSQL_ASSOC);
print_r($ans);
mysql_close($con);
?>
mysql_fetch_assoc()
This function allows you to retrieve a record from the recordset that is returned from executing
the MySQL query in the form of associative array.
Syntax:
mysql_fetch_assoc(VariableName)
Returns an associative array that corresponds to the fetched row, or FALSE if there are no more
rows.
Example:
<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query, $conn);
$ans=mysql_fetch_assoc($result);
print_r($ans);
mysql_close($con);
?>
1
5 – Web Extension: PHP and XML
To go through all the records fetched in record set.
<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query, $conn);
while($ans=mysql_fetch_assoc($result))
{
echo $ans*‘field1’+.”<br>”;
echo $ans*‘field2’+.”<br>”;
}
mysql_close($con);
?>
mysql_num_rows()
This function allows you to retrieve number of records available in the record set.
Syntax:
mysql_num_rows(ResultVariable);
ResultVariable is the variable that holds result returned by mysql_query() function.
Example:
<?php
$conn=mysql_connect(“localhost”,”root”,””);
$db=mysql_select_db(“Mydatabse”, $conn);
$query=”select * from product_master”;
$result=mysql_query($query, $conn);
$total_records=mysql_fetch_rows($result);
echo “Total Records:”.$total_records;
mysql_close($con);
?>
mysql_error()
This function allows you to retrieve theerror text from the most recently executed MySQL
function.
If no error encountered while executing the script then it will returns blank string.
If the mysql operation contains more than one error then it will returns error description of the
last statement in which error is encountered.
Syntax:
mysql_error();
1
5 – Web Extension: PHP and XML
Example:
<?php $conn=mysql_connect(“localhost”,”root”,””);
if($conn)
{
}
else
{
}
?>
1
5 – Web Extension: PHP and XML
echo “Connected with
MySQL”;
echo
“Error:”.mysql_error()
;
mysql_close()
This function allows you to close the connection that is established using mysql_connect()
function.
Syntax:mysql_close(ConnectionName);
ConnectionName :- Indicates the name of the variable that is used at the time of establish
connection with MySQL server using mysql_connect() function.
It returns true is connection is closed successfully otherwise it returns false.
Example:
<?php
$conn=mysql_connect(“localhost”,”root”,””);
mysql_close($con);
?>