0% found this document useful (0 votes)
249 views88 pages

PHP Tutorial - W3schools2 PDF

The document provides information about connecting PHP to MySQL databases. It discusses that MySQL is a popular database system used with PHP. It then defines what MySQL is, how data is stored in tables with columns and rows, and how databases are useful for storing categorized information. It also covers connecting PHP to MySQL using MySQLi and PDO extensions, and provides examples of creating a database and table in MySQL through PHP.

Uploaded by

viru991
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
249 views88 pages

PHP Tutorial - W3schools2 PDF

The document provides information about connecting PHP to MySQL databases. It discusses that MySQL is a popular database system used with PHP. It then defines what MySQL is, how data is stored in tables with columns and rows, and how databases are useful for storing categorized information. It also covers connecting PHP to MySQL using MySQLi and PDO extensions, and provides examples of creating a database and table in MySQL through PHP.

Uploaded by

viru991
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 88

PHP Tutorial (Part -2)

PHP MySQL Database


With PHP, you can connect to and manipulate databases.
MySQL is the most popular database system used with PHP.

What is MySQL?
 MySQL is a database system used on the web
 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL
 MySQL compiles on a number of platforms
 MySQL is free to download and use
 MySQL is developed, distributed, and supported by Oracle Corporation
 MySQL is named after co-founder Monty Widenius's daughter: My

The data in a MySQL database are stored in tables. A table is a collection of related data, and it
consists of columns and rows.

Databases are useful for storing information categorically. A company may have a database with
the following tables:

 Employees
 Products
 Customers
 Orders

PHP + MySQL Database System


 PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix
platform)

Database Queries
A query is a question or a request.

We can query a database for specific information and have a recordset returned.

Look at the following query (using standard SQL):

SELECT LastName FROM Employees

The query above selects all the data in the "LastName" column from the "Employees" table.

To learn more about SQL, please visit our SQL tutorial.


Download MySQL Database
If you don't have a PHP server with a MySQL Database, you can download it for free here:
http://www.mysql.com

Facts About MySQL Database


MySQL is the de-facto standard database system for web sites with HUGE volumes of both data
and end-users (like Facebook, Twitter, and Wikipedia).

Another great thing about MySQL is that it can be scaled down to support embedded database
applications.

Look at http://www.mysql.com/customers/ for an overview of companies using MySQL.

PHP Connect to MySQL


PHP 5 and later can work with a MySQL database using:
 MySQLi extension (the "i" stands for improved)
 PDO (PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in
2012.

Should I Use MySQLi or PDO?


If you need a short answer, it would be "Whatever you like".
Both MySQLi and PDO have their advantages:
PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL
databases.
So, if you have to switch your project to use another database, PDO makes the process easy. You
only have to change the connection string and a few queries. With MySQLi, you will need to
rewrite the entire code - queries included.
Both are object-oriented, but MySQLi also offers a procedural API.
Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very
important for web application security.

MySQL Examples in Both MySQLi and PDO Syntax


In this, and in the following chapters we demonstrate three ways of working with PHP and
MySQL:

 MySQLi (object-oriented)
 MySQLi (procedural)
 PDO

MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed in most cases, when
php5 mysql package is installed.
For installation details, go to: http://php.net/manual/en/mysqli.installation.php

PDO Installation
For installation details, go to: http://php.net/manual/en/pdo.installation.php

Open a Connection to MySQL


Before we can access data in the MySQL database, we need to be able to connect to the server:

Example (MySQLi Object-Oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Note on the object-oriented example above:

$connect_error was broken until PHP 5.2.9 and 5.3.0. If you need to ensure compatibility with
PHP versions prior to 5.2.9 and 5.3.0, use the following code instead:

// Check connection
if (mysqli_connect_error()) {
die("Database connection failed: " . mysqli_connect_error());
}

Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Example (PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

Note: In the PDO example above we have also specified a database (myDB). PDO require a
valid database to connect to. If no database is specified, an exception is thrown.

Tip: A great benefit of PDO is that it has an exception class to handle any problems that may
occur in our database queries. If an exception is thrown within the try{ } block, the script stops
executing and flows directly to the first catch(){ } block.

Close the Connection


The connection will be closed automatically when the script ends. To close the connection
before, use the following:

MySQLi Object-Oriented:
$conn->close();

MySQLi Procedural:
mysqli_close($conn);

PDO:
$conn = null;
PHP Create a MySQL Database

A database consists of one or more tables.

You will need special CREATE privileges to create or to delete a MySQL database.

Create a MySQL Database Using MySQLi and PDO


The CREATE DATABASE statement is used to create a database in MySQL.

The following examples create a database named "myDB":

Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

Note: When you create a new database, you must only specify the first three arguments to the
mysqli object (servername, username and password).

Tip: If you have to use a specific port, add an empty string for the database-name argument, like
this: new mysqli("localhost", "username", "password", "", port)

Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Note: The following PDO example create a database named "myDBPDO":

Example (PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
// use exec() because no results are returned
$conn->exec($sql);
echo "Database created successfully<br>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

Tip: A great benefit of PDO is that it has exception class to handle any problems that may occur
in our database queries. If an exception is thrown within the try{ } block, the script stops
executing and flows directly to the first catch(){ } block. In the catch block above we echo the
SQL statement and the generated error message.
PHP MySQL Create Table
A database table has its own unique name and consists of columns and rows.

Create a MySQL Table Using MySQLi and PDO


The CREATE TABLE statement is used to create a table in MySQL.

We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname",
"email" and "reg_date":

CREATE TABLE MyGuests (


id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

Notes on the table above:

The data type specifies what type of data the column can hold. For a complete reference of all the
available data types, go to our Data Types reference.

After the data type, you can specify other optional attributes for each column:

 NOT NULL - Each row must contain a value for that column, null values are not allowed
 DEFAULT value - Set a default value that is added when no other value is passed
 UNSIGNED - Used for number types, limits the stored data to positive numbers and zero
 AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each time a new
record is added
 PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY KEY
setting is often an ID number, and is often used with AUTO_INCREMENT

Each table should have a primary key column (in this case: the "id" column). Its value must be
unique for each record in the table.

The following examples shows how to create the table in PHP:

Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {


echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";

if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Example (PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";

// use exec() because no results are returned


$conn->exec($sql);
echo "Table MyGuests created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>
PHP MySQL Insert Data

Insert Data Into MySQL Using MySQLi and PDO


After a database and a table have been created, we can start adding data in them.

Here are some syntax rules to follow:

 The SQL query must be quoted in PHP


 String values inside the SQL query must be quoted
 Numeric values must not be quoted
 The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...)


VALUES (value1, value2, value3,...)

To learn more about SQL, please visit our SQL tutorial.

In the previous chapter we created an empty table named "MyGuests" with five columns: "id",
"firstname", "lastname", "email" and "reg_date". Now, let us fill the table with data.

Note: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP with default
update of current_timesamp (like the "reg_date" column), it is no need to be specified in the SQL
query; MySQL will automatically add the value.

The following examples add a new record to the "MyGuests" table:

Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

Example (PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>
PHP MySQL Get Last Inserted ID

Get ID of The Last Inserted Record


If we perform an INSERT or UPDATE on a table with an AUTO_INCREMENT field, we can
get the ID of the last inserted/updated record immediately.

In the table "MyGuests", the "id" column is an AUTO_INCREMENT field:

CREATE TABLE MyGuests (


id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

The following examples are equal to the examples from the previous page (PHP Insert Data Into
MySQL), except that we have added one single line of code to retrieve the ID of the last inserted
record. We also echo the last inserted ID:

Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {


$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

Example (PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>
PHP MySQL Insert Multiple Records
Insert Multiple Records Into MySQL Using MySQLi and
PDO
Multiple SQL statements must be executed with the mysqli_multi_query() function.
The following examples add three new records to the "MyGuests" table:
Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')";

if ($conn->multi_query($sql) === TRUE) {


echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
 Note that each SQL statement must be separated by a semicolon.

Example (MySQLi Procedural)


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')";

if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>
The PDO way is a little bit different:
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// begin the transaction


$conn->beginTransaction();
// our SQL statements
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')");
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com')");
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')");

// commit the transaction


$conn->commit();
echo "New records created successfully";
}
catch(PDOException $e)
{
// roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
}

$conn = null;
?>
PHP MySQL Prepared Statements

Prepared statements are very useful against SQL injections.

Prepared Statements and Bound Parameters


A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly
with high efficiency.

Prepared statements basically work like this:

1. Prepare: An SQL statement template is created and sent to the database. Certain values
are left unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests
VALUES(?, ?, ?)
2. The database parses, compiles, and performs query optimization on the SQL statement
template, and stores the result without executing it
3. Execute: At a later time, the application binds the values to the parameters, and the
database executes the statement. The application may execute the statement as many
times as it wants with different values

Compared to executing SQL statements directly, prepared statements have three main
advantages:

 Prepared statements reduce parsing time as the preparation on the query is done only once
(although the statement is executed multiple times)
 Bound parameters minimize bandwidth to the server as you need send only the parameters
each time, and not the whole query
 Prepared statements are very useful against SQL injections, because parameter values,
which are transmitted later using a different protocol, need not be correctly escaped. If the
original statement template is not derived from external input, SQL injection cannot
occur.

Prepared Statements in MySQLi


The following example uses prepared statements and bound parameters in MySQLi:

Example (MySQLi with Prepared Statements)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// prepare and bind


$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?,
?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

// set parameters and execute


$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();

$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();

echo "New records created successfully";

$stmt->close();
$conn->close();
?>

Code lines to explain from the example above:

"INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"

In our SQL, we insert a question mark (?) where we want to substitute in an integer, string,
double or blob value.

Then, have a look at the bind_param() function:

$stmt->bind_param("sss", $firstname, $lastname, $email);

This function binds the parameters to the SQL query and tells the database what the parameters
are. The "sss" argument lists the types of data that the parameters are. The s character tells mysql
that the parameter is a string.

The argument may be one of four types:

 i - integer
 d - double
 s - string
 b - BLOB

We must have one of these for each parameter.

By telling mysql what type of data to expect, we minimize the risk of SQL injections.

Note: If we want to insert any data from external sources (like user input), it is very important
that the data is sanitized and validated.
Prepared Statements in PDO
The following example uses prepared statements and bound parameters in PDO:

Example (PDO with Prepared Statements)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// prepare sql and bind parameters


$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);

// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

// insert another row


$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();

// insert another row


$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();

echo "New records created successfully";


}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
PHP MySQL Select Data

Select Data From a MySQL Database


The SELECT statement is used to select data from one or more tables:

SELECT column_name(s) FROM table_name

or we can use the * character to select ALL columns from a table:

SELECT * FROM table_name

To learn more about SQL, please visit our SQL tutorial.

Select Data With MySQLi


The following example selects the id, firstname and lastname columns from the MyGuests table
and displays it on the page:

Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Ouput
id: 1 - Name: John Doe
id: 2 - Name: Mary Moe
id: 3 - Name: Julie Dooley
Code lines to explain from the example above:

First, we set up an SQL query that selects the id, firstname and lastname columns from the
MyGuests table. The next line of code runs the query and puts the resulting data into a variable
called $result.

Then, the function num_rows() checks if there are more than zero rows returned.

If there are more than zero rows returned, the function fetch_assoc() puts all the results into an
associative array that we can loop through. The while() loop loops through the result set and
outputs the data from the id, firstname and lastname columns.

The following example shows the same as the example above, in the MySQLi procedural way:

Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>

Output

id: 1 - Name: John Doe


id: 2 - Name: Mary Moe
id: 3 - Name: Julie Dooley

You can also put the result in an HTML table:


Example (MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstname"]."
".$row["lastname"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>

Ouput
ID Name
1 John Doe
2 Mary Moe
3 Julie Dooley

Select Data With PDO (+ Prepared Statements)


The following example uses prepared statements.

It selects the id, firstname and lastname columns from the MyGuests table and displays it in an
HTML table:

Example (PDO)

<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

class TableRows extends RecursiveIteratorIterator {


function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}

function current() {
return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
}

function beginChildren() {
echo "<tr>";
}

function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests");
$stmt->execute();

// set the resulting array to associative


$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

Output

Id Firstname Lastname
1 John Doe
2 Mary Moe
3 Julie Dooley
PHP MySQL Use The WHERE Clause

Select and Filter Data From a MySQL Database


The WHERE clause is used to filter records.

The WHERE clause is used to extract only those records that fulfill a specified condition.

SELECT column_name(s) FROM table_name WHERE column_name operator value

To learn more about SQL, please visit our SQL tutorial.

Select and Filter Data With MySQLi


The following example selects the id, firstname and lastname columns from the MyGuests table
where the lastname is "Doe", and displays it on the page:

Example (MySQLi Object-oriented)

<!DOCTYPE html>
<html>
<body>

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"] . "<br>";
}
} else {
echo "0 results";
}

$conn->close();
?>

</body>
</html>
Output

id: 1 - Name: John Doe


id: 2 - Name: Mary Doe
id: 3 - Name: Julie Doe

Code lines to explain from the example above:

First, we set up the SQL query that selects the id, firstname and lastname columns from the
MyGuests table where the lastname is "Doe". The next line of code runs the query and puts the
resulting data into a variable called $result.

Then, the function num_rows() checks if there are more than zero rows returned.

If there are more than zero rows returned, the function fetch_assoc() puts all the results into an
associative array that we can loop through. The while() loop loops through the result set and
outputs the data from the id, firstname and lastname columns.

The following example shows the same as the example above, in the MySQLi procedural way:

Example (MySQLi Procedural)

<!DOCTYPE html>
<html>
<body>

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'";


$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>

</body>
</html>
Output
id: 1 - Name: John Doe
id: 2 - Name: Mary Doe
id: 3 - Name: Julie Doe
You can also put the result in an HTML table:

Example (MySQLi Object-oriented)

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["firstname"]. " " . $row["lastname"].
"</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}

$conn->close();
?>

</body>
</html>

Output

Id Firstname Lastname
1 John Doe
2 Mary Moe
3 Julie Dooley
Select Data With PDO (+ Prepared Statements)
The following example uses prepared statements.

It selects the id, firstname and lastname columns from the MyGuests table where the lastname is
"Doe", and displays it in an HTML table:

Example (PDO)

<!DOCTYPE html>
<html>
<body>

<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

class TableRows extends RecursiveIteratorIterator {


function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}

function current() {
return "<td style='width: 150px; border: 1px solid black;'>" . parent::current(). "</td>";
}

function beginChildren() {
echo "<tr>";
}

function endChildren() {
echo "</tr>" . "\n";
}
}

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests WHERE
lastname='Doe'");
$stmt->execute();

// set the resulting array to associative


$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {


echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

</body>
</html>
PHP MySQL Use The ORDER BY Clause

Select and Order Data From a MySQL Database


The ORDER BY clause is used to sort the result-set in ascending or descending order.
The ORDER BY clause sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.
SELECT column_name(s) FROM table_name ORDER BY column_name(s) ASC|DESC
To learn more about SQL, please visit our SQL tutorial.

Select and Order Data With MySQLi


The following example selects the id, firstname and lastname columns from the MyGuests table.
The records will be ordered by the lastname column:

Example (MySQLi Object-oriented)

<!DOCTYPE html>
<html>
<body>

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"] . "<br>";
}
} else {
echo "0 results";
}

$conn->close();
?>

</body>
</html>

Code lines to explain from the example above:

First, we set up the SQL query that selects the id, firstname and lastname columns from the
MyGuests table. The records will be ordered by the lastname column. The next line of code runs
the query and puts the resulting data into a variable called $result.

Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an
associative array that we can loop through. The while() loop loops through the result set and
outputs the data from the id, firstname and lastname columns.

The following example shows the same as the example above, in the MySQLi procedural way:

Example (MySQLi Procedural)

<!DOCTYPE html>
<html>
<body>

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname";


$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}

mysqli_close($conn);
?>

</body>
</html>

You can also put the result in an HTML table:

Example (MySQLi Object-oriented)

<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, firstname, lastname FROM MyGuests ORDER BY lastname";


$result = $conn->query($sql);

if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "</td><td>" . $row["firstname"]. " " . $row["lastname"].
"</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}

$conn->close();
?>

</body>
</html>

Select Data With PDO (+ Prepared Statements)


The following example uses prepared statements.

Here we select the id, firstname and lastname columns from the MyGuests table. The records will
be ordered by the lastname column, and it will be displayed in an HTML table:

Example (PDO)

<!DOCTYPE html>
<html>
<body>

<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

class TableRows extends RecursiveIteratorIterator {


function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}

function current() {
return "<td style='width: 150px; border: 1px solid black;'>" . parent::current(). "</td>";
}

function beginChildren() {
echo "<tr>";
}

function endChildren() {
echo "</tr>" . "\n";
}
}

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests ORDER BY
lastname");
$stmt->execute();

// set the resulting array to associative


$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {


echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

</body>
</html>
PHP MySQL Delete Data

Delete Data From a MySQL Table Using MySQLi and PDO


The DELETE statement is used to delete records from a table:

DELETE FROM table_name


WHERE some_column = some_value

Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which
record or records that should be deleted. If you omit the WHERE clause, all records will be
deleted!

To learn more about SQL, please visit our SQL tutorial.

Let's look at the "MyGuests" table:

id firstname lastname email reg_date

1 John Doe john@example.com 2014-10-22 14:26:15

2 Mary Moe mary@example.com 2014-10-23 10:22:30

3 Julie Dooley julie@example.com 2014-10-26 10:48:23

The following examples delete the record with id=3 in the "MyGuests" table:

Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

if ($conn->query($sql) === TRUE) {


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}

$conn->close();
?>
Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Example (PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

// use exec() because no results are returned


$conn->exec($sql);
echo "Record deleted successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

After the record is deleted, the table will look like this:

id firstname lastname email reg_date

1 John Doe john@example.com 2014-10-22 14:26:15

2 Mary Moe mary@example.com 2014-10-23 10:22:30


PHP MySQL Update Data

Update Data In a MySQL Table Using MySQLi and PDO


The UPDATE statement is used to update existing records in a table:

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Notice the WHERE clause in the UPDATE syntax: The WHERE clause specifies which
record or records that should be updated. If you omit the WHERE clause, all records will be
updated!

To learn more about SQL, please visit our SQL tutorial.

Let's look at the "MyGuests" table:

id firstname lastname email reg_date

1 John Doe john@example.com 2014-10-22 14:26:15

2 Mary Moe mary@example.com 2014-10-23 10:22:30

The following examples update the record with id=2 in the "MyGuests" table:

Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if ($conn->query($sql) === TRUE) {


echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
?>
Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

Example (PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

// Prepare statement
$stmt = $conn->prepare($sql);

// execute the query


$stmt->execute();

// echo a message to say the UPDATE succeeded


echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>
After the record is updated, the table will look like this:

id firstname lastname email reg_date

1 John Doe john@example.com 2014-10-22 14:26:15

2 Mary Doe mary@example.com 2014-10-23 10:22:30

PHP MySQL Limit Data Selections

Limit Data Selections From a MySQL Database


MySQL provides a LIMIT clause that is used to specify the number of records to return.

The LIMIT clause makes it easy to code multi page results or pagination with SQL, and is very
useful on large tables. Returning a large number of records can impact on performance.

Assume we wish to select all records from 1 - 30 (inclusive) from a table called "Orders". The
SQL query would then look like this:

$sql = "SELECT * FROM Orders LIMIT 30";

When the SQL query above is run, it will return the first 30 records.

What if we want to select records 16 - 25 (inclusive)?

Mysql also provides a way to handle this: by using OFFSET.

The SQL query below says "return only 10 records, start on record 16 (OFFSET 15)":

$sql = "SELECT * FROM Orders LIMIT 10 OFFSET 15";

You could also use a shorter syntax to achieve the same result:

$sql = "SELECT * FROM Orders LIMIT 15, 10";

Notice that the numbers are reversed when you use a comma.
PHP XML Parsers

What is XML?
The XML language is a way to structure data for sharing across websites.

Several web technologies like RSS Feeds and Podcasts are written in XML.

XML is easy to create. It looks a lot like HTML, except that you make up your own tags.

If you want to learn more about XML, please visit our XML tutorial.

What is an XML Parser?


To read and update, create and manipulate an XML document, you will need an XML parser.

In PHP there are two major types of XML parsers:

 Tree-Based Parsers
 Event-Based Parsers

Tree-Based Parsers
Tree-based parsers holds the entire document in Memory and transforms the XML document into
a Tree structure. It analyzes the whole document, and provides access to the Tree elements
(DOM).

This type of parser is a better option for smaller XML documents, but not for large XML
document as it causes major performance issues.

Example of tree-based parsers:

 SimpleXML
 DOM

Event-Based Parsers
Event-based parsers do not hold the entire document in Memory, instead, they read in one node at
a time and allow you to interact with in real time. Once you move onto the next node, the old one
is thrown away.

This type of parser is well suited for large XML documents. It parses faster and consumes less
memory.

Example of event-based parsers:

 XMLReader
 XML Expat Parser
PHP SimpleXML Parser
SimpleXML is a PHP extension that allows us to easily manipulate and get XML data.

The SimpleXML Parser


SimpleXML is a tree-based parser.
SimpleXML provides an easy way of getting an element's name, attributes and textual content if
you know the XML document's structure or layout.
SimpleXML turns an XML document into a data structure you can iterate through like a
collection of arrays and objects.
Compared to DOM or the Expat parser, SimpleXML takes a fewer lines of code to read text data
from an element.

Installation
From PHP 5, the SimpleXML functions are part of the PHP core. No installation is required to
use these functions.

PHP SimpleXML - Read From String


The PHP simplexml_load_string() function is used to read XML data from a string.
Assume we have a variable that contains XML data, like this:
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";

The example below shows how to use the simplexml_load_string() function to read XML
data from a string:

Example

PHP program Output


<?php SimpleXMLElement Object ( [to] => Tove [from]
$myXMLData = => Jani [heading] => Reminder [body] => Don't
"<?xml version='1.0' encoding='UTF-8'?> forget me this weekend! )
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>";
$xml=simplexml_load_string($myXMLData)
or die("Error: Cannot create object");
print_r($xml);
?>
The output of the code above will be:

SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] => Reminder [body] =>
Don't forget me this weekend! )

Error Handling Tip: Use the libxml functionality to retrieve all XML errors when loading the
document and then iterate over the errors. The following example tries to load a broken XML
string:

Example

<?php
libxml_use_internal_errors(true);
$myXMLData =
"<?xml version='1.0' encoding='UTF-8'?>
<document>
<user>John Doe</wronguser>
<email>john@example.com</wrongemail>
</document>";

$xml = simplexml_load_string($myXMLData);
if ($xml === false) {
echo "Failed loading XML: ";
foreach(libxml_get_errors() as $error) {
echo "<br>", $error->message;
}
} else {
print_r($xml);
}
?>

The output of the code above will be:

Failed loading XML:


Opening and ending tag mismatch: user line 3 and wronguser
Opening and ending tag mismatch: email line 4 and wrongemail

PHP SimpleXML - Read From File


The PHP simplexml_load_file() function is used to read XML data from a file.

Assume we have an XML file called "note.xml", that looks like this:

<?xml version="1.0" encoding="UTF-8"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The example below shows how to use the simplexml_load_file() function to read XML data
from a file:

Example

<?php
$xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
print_r($xml);
?>
The output of the code above will be:

SimpleXMLElement Object ( [to] => Tove [from] => Jani [heading] => Reminder [body] => Don't forget me
this weekend! )

Tip: The next chapter shows how to get/retrieve node values from an XML file with
SimpleXML!

PHP SimpleXML - Get Node/Attribute Values

SimpleXML is a PHP extension that allows us to easily manipulate and get XML data.

PHP SimpleXML - Get Node Values


Get the node values from the "note.xml" file:

Example

<?php
$xml=simplexml_load_file("note.xml") or die("Error: Cannot create object");
echo $xml->to . "<br>";
echo $xml->from . "<br>";
echo $xml->heading . "<br>";
echo $xml->body;
?>

The output of the code above will be:

Tove
Jani
Reminder
Don't forget me this weekend!

Another XML File


Assume we have an XML file called "books.xml", that looks like this:

<?xml version="1.0" encoding="utf-8"?>


<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en-us">XQuery Kick Start</title>
<author>James McGovern</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="WEB">
<title lang="en-us">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

PHP SimpleXML - Get Node Values of Specific Elements


The following example gets the node value of the <title> element in the first and second <book>
elements in the "books.xml" file:

Example

<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
echo $xml->book[0]->title . "<br>";
echo $xml->book[1]->title;
?>

The output of the code above will be:

Everyday Italian
Harry Potter

PHP SimpleXML - Get Node Values - Loop


The following example loops through all the <book> elements in the "books.xml" file, and gets
the node values of the <title>, <author>, <year>, and <price> elements:

Example

<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
foreach($xml->children() as $books) {
echo $books->title . ", ";
echo $books->author . ", ";
echo $books->year . ", ";
echo $books->price . "<br>";
}
?>

The output of the code above will be:

Everyday Italian, Giada De Laurentiis, 2005, 30.00


Harry Potter, J K. Rowling, 2005, 29.99
XQuery Kick Start, James McGovern, 2003, 49.99
Learning XML, Erik T. Ray, 2003, 39.95

PHP SimpleXML - Get Attribute Values


The following example gets the attribute value of the "category" attribute of the first <book>
element and the attribute value of the "lang" attribute of the <title> element in the second <book>
element:
Example

<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
echo $xml->book[0]['category'] . "<br>";
echo $xml->book[1]->title['lang'];
?>

The output of the code above will be:

COOKING
en

PHP SimpleXML - Get Attribute Values - Loop


The following example gets the attribute values of the <title> elements in the "books.xml" file:

Example

<?php
$xml=simplexml_load_file("books.xml") or die("Error: Cannot create object");
foreach($xml->children() as $books) {
echo $books->title['lang'];
echo "<br>";
}
?>
The output of the code above will be:
en
en
en-us
en-us
PHP XML Expat Parser

The built-in XML Expat Parser makes it possible to process XML documents in PHP.

The XML Expat Parser


The Expat parser is an event-based parser.

Look at the following XML fraction:

<from>Jani</from>

An event-based parser reports the XML above as a series of three events:

 Start element: from


 Start CDATA section, value: Jani
 Close element: from

The XML Expat Parser functions are part of the PHP core. There is no installation needed to use
these functions.

The XML File


The XML file "note.xml" will be used in the example below:

<?xml version="1.0" encoding="UTF-8"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Initializing the XML Expat Parser


We want to initialize the XML Expat Parser in PHP, define some handlers for different XML
events, and then parse the XML file.

Example

<?php
// Initialize the XML parser
$parser=xml_parser_create();

// Function to use at the start of an element


function start($parser,$element_name,$element_attrs) {
switch($element_name) {
case "NOTE":
echo "-- Note --<br>";
break;
case "TO":
echo "To: ";
break;
case "FROM":
echo "From: ";
break;
case "HEADING":
echo "Heading: ";
break;
case "BODY":
echo "Message: ";
}
}

// Function to use at the end of an element


function stop($parser,$element_name) {
echo "<br>";
}

// Function to use when finding character data


function char($parser,$data) {
echo $data;
}

// Specify element handler


xml_set_element_handler($parser,"start","stop");

// Specify data handler


xml_set_character_data_handler($parser,"char");

// Open XML file


$fp=fopen("note.xml","r");

// Read data
while ($data=fread($fp,4096)) {
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}

// Free the XML parser


xml_parser_free($parser);
?>

Output

-- Note --
To: Tove
From: Jani
Heading: Reminder
Message: Don't forget me this weekend!

Example explained:

1. Initialize the XML parser with the xml_parser_create() function


2. Create functions to use with the different event handlers
3. Add the xml_set_element_handler() function to specify which function will be
executed when the parser encounters the opening and closing tags
4. Add the xml_set_character_data_handler() function to specify which function will
execute when the parser encounters character data
5. Parse the file "note.xml" with the xml_parse() function
6. In case of an error, add xml_error_string() function to convert an XML error to a
textual description
7. Call the xml_parser_free() function to release the memory allocated with the
xml_parser_create() function
PHP XML DOM Parser

The built-in DOM parser makes it possible to process XML documents in PHP.

The XML DOM Parser


The DOM parser is a tree-based parser.

Look at the following XML document fraction:

<?xml version="1.0" encoding="UTF-8"?>


<from>Jani</from>

The DOM sees the XML above as a tree structure:

 Level 1: XML Document


 Level 2: Root element: <from>
 Level 3: Text element: "Jani"

Installation
The DOM parser functions are part of the PHP core. There is no installation needed to use these
functions.

The XML File


The XML file below ("note.xml") will be used in our example:

<?xml version="1.0" encoding="UTF-8"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

Load and Output XML


We want to initialize the XML parser, load the xml, and output it:

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

print $xmlDoc->saveXML();
?>

The output of the code above will be:

Tove Jani Reminder Don't forget me this weekend!


If you select "View source" in the browser window, you will see the following HTML:

<?xml version="1.0" encoding="UTF-8"?>


<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The example above creates a DOMDocument-Object and loads the XML from "note.xml" into it.

Then the saveXML() function puts the internal XML document into a string, so we can output it.

Looping through XML


We want to initialize the XML parser, load the XML, and loop through all elements of the
<note> element:

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");

$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item) {
print $item->nodeName . " = " . $item->nodeValue . "<br>";
}
?>

The output of the code above will be:

#text =
to = Tove
#text =
from = Jani
#text =
heading = Reminder
#text =
body = Don't forget me this weekend!
#text =

In the example above you see that there are empty text nodes between each element.

When XML generates, it often contains white-spaces between the nodes. The XML DOM parser
treats these as ordinary elements, and if you are not aware of them, they sometimes cause
problems.
PHP - AJAX

PHP - AJAX Introduction

AJAX is about updating parts of a web page, without reloading the whole page.

What is AJAX?
AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small amounts of data
with the server behind the scenes. This means that it is possible to update parts of a web page,
without reloading the whole page.

Classic web pages, (which do not use AJAX) must reload the entire page if the content should
change.

Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.

How AJAX Works

AJAX is Based on Internet Standards


AJAX is based on internet standards, and uses a combination of:

 XMLHttpRequest object (to exchange data asynchronously with a server)


 JavaScript/DOM (to display/interact with the information)
 CSS (to style the data)
 XML (often used as the format for transferring data)

AJAX applications are browser- and platform-independent!


Google Suggest
AJAX was made popular in 2005 by Google, with Google Suggest.

Google Suggest is using AJAX to create a very dynamic web interface: When you start typing in
Google's search box, a JavaScript sends the letters off to a server and the server returns a list of
suggestions.

Start Using AJAX Today


In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without
reloading the whole page. The server script will be written in PHP.

If you want to learn more about AJAX, visit our AJAX tutorial.

PHP - AJAX and PHP

AJAX is used to create more interactive applications.

AJAX PHP Example


The following example will demonstrate how a web page can communicate with a web server
while a user type characters in an input field:

Example Explained
In the example above, when a user types a character in the input field, a function called
"showHint()" is executed.

The function is triggered by the onkeyup event.

Here is the HTML code:


Example

<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>

<p><b>Start typing a name in the input field below:</b></p>


<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>

Output

Code explanation:

First, check if the input field is empty (str.length == 0). If it is, clear the content of the txtHint
placeholder and exit the function.

However, if the input field is not empty, do the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a PHP file (gethint.php) on the server
 Notice that q parameter is added to the url (gethint.php?q="+str)
 And the str variable holds the content of the input field

The PHP File - "gethint.php"


The PHP file checks an array of names, and returns the corresponding name(s) to the browser:
<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";

// get the q parameter from URL


$q = $_REQUEST["q"];

$hint = "";

// lookup all hints from array if $q is different from ""


if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}

// Output "no suggestion" if no hint was found or output correct values


echo $hint === "" ? "no suggestion" : $hint;
?>
PHP - AJAX and MySQL
AJAX can be used for interactive communication with a database.

AJAX Database Example


The following example will demonstrate how a web page can fetch information from a database
with AJAX:

Example Explained - The MySQL Database


The database table we use in the example above looks like this:

id FirstName LastName Age Hometown Job


1 Peter Griffin 41 Quahog Brewery
2 Lois Griffin 40 Newport Piano Teacher
3 Joseph Swanson 39 Quahog Police Officer
4 Glenn Quagmire 41 Quahog Pilot

Example Explained
In the example above, when a user selects a person in the dropdown list above, a function called
"showUser()" is executed.

The function is triggered by the onchange event.

Here is the HTML code:

Example

<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>

</body>
</html>

Output

Code explanation:

First, check if person is selected. If no person is selected (str == ""), clear the content of txtHint
and exit the function. If a person is selected, do the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

The PHP File


The page on the server called by the JavaScript above is a PHP file called "getuser.php".

The source code in "getuser.php" runs a query against a MySQL database, and returns the result
in an HTML table:

<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}

table, td, th {
border: 1px solid black;
padding: 5px;
}

th {text-align: left;}
</style>
</head>
<body>

<?php
$q = intval($_GET['q']);

$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);

echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>

Explanation: When the query is sent from the JavaScript to the PHP file, the following happens:

1. PHP opens a connection to a MySQL server


2. The correct person is found
3. An HTML table is created, filled with data, and sent back to the "txtHint" placeholder
PHP Example - AJAX and XML
AJAX can be used for interactive communication with an XML file.

AJAX XML Example


The following example will demonstrate how a web page can fetch information from an XML
file with AJAX:

Example Explained - The HTML Page


When a user selects a CD in the dropdown list above, a function called "showCD()" is executed.
The function is triggered by the "onchange" event:
<html>
<head>
<script>
function showCD(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getcd.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
Select a CD:
<select name="cds" onchange="showCD(this.value)">
<option value="">Select a CD:</option>
<option value="Bob Dylan">Bob Dylan</option>
<option value="Bee Gees">Bee Gees</option>
<option value="Cat Stevens">Cat Stevens</option>
</select>
</form>
<div id="txtHint"><b>CD info will be listed here...</b></div>
</body>
</html>

The showCD() function does the following:

 Check if a CD is selected
 Create an XMLHttpRequest object
 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

The PHP File


The page on the server called by the JavaScript above is a PHP file called "getcd.php".

The PHP script loads an XML document, "cd_catalog.xml", runs a query against the XML file,
and returns the result as HTML:

<?php
$q=$_GET["q"];

$xmlDoc = new DOMDocument();


$xmlDoc->load("cd_catalog.xml");

$x=$xmlDoc->getElementsByTagName('ARTIST');

for ($i=0; $i<=$x->length-1; $i++) {


//Process only element nodes
if ($x->item($i)->nodeType==1) {
if ($x->item($i)->childNodes->item(0)->nodeValue == $q) {
$y=($x->item($i)->parentNode);
}
}
}

$cd=($y->childNodes);

for ($i=0;$i<$cd->length;$i++) {
//Process only element nodes
if ($cd->item($i)->nodeType==1) {
echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("<br>");
}
}
?>

When the CD query is sent from the JavaScript to the PHP page, the following happens:

1. PHP creates an XML DOM object


2. Find all <artist> elements that matches the name sent from the JavaScript
3. Output the album information (send to the "txtHint" placeholder)
PHP Example - AJAX Live Search

AJAX can be used to create more user-friendly and interactive searches.

AJAX Live Search


The following example will demonstrate a live search, where you get search results while you
type.

Live search has many benefits compared to traditional searching:

 Results are shown as you type


 Results narrow as you continue typing
 If results become too narrow, remove characters to see a broader result

Search for a W3Schools page in the input field below:

The results in the example above are found in an XML file (links.xml). To make this example
small and simple, only six results are available.

Example Explained - The HTML Page


When a user types a character in the input field above, the function "showResult()" is executed.
The function is triggered by the "onkeyup" event:

<html>
<head>
<script>
function showResult(str) {
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("livesearch").innerHTML=this.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>

</body>
</html>

Source code explanation:

If the input field is empty (str.length==0), the function clears the content of the livesearch
placeholder and exits the function.

If the input field is not empty, the showResult() function executes the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (q) is added to the URL (with the content of the input field)

The PHP File


The page on the server called by the JavaScript above is a PHP file called "livesearch.php".

The source code in "livesearch.php" searches an XML file for titles matching the search string
and returns the result:

<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");

$x=$xmlDoc->getElementsByTagName('link');

//get the q parameter from URL


$q=$_GET["q"];

//lookup all links from the xml file if length of q>0


if (strlen($q)>0) {
$hint="";
for($i=0; $i<($x->length); $i++) {
$y=$x->item($i)->getElementsByTagName('title');
$z=$x->item($i)->getElementsByTagName('url');
if ($y->item(0)->nodeType==1) {
//find a link matching the search text
if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {
if ($hint=="") {
$hint="<a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
} else {
$hint=$hint . "<br /><a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
}
}
}
}

// Set output to "no suggestion" if no hint was found


// or to the correct values
if ($hint=="") {
$response="no suggestion";
} else {
$response=$hint;
}

//output the response


echo $response;
?>

Ouput

If there is any text sent from the JavaScript (strlen($q) > 0), the following happens:

 Load an XML file into a new XML DOM object


 Loop through all <title> elements to find matches from the text sent from the JavaScript
 Sets the correct url and title in the "$response" variable. If more than one match is found,
all matches are added to the variable
 If no matches are found, the $response variable is set to "no suggestion"

PHP Example - AJAX Poll

AJAX Poll
The following example will demonstrate a poll where the result is shown without reloading.

Do you like PHP and AJAX so far?

Yes:
No:

Example Explained - The HTML Page


When a user chooses an option above, a function called "getVote()" is executed. The function is
triggered by the "onclick" event:

<html>
<head>
<script>
function getVote(int) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("poll").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","poll_vote.php?vote="+int,true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="poll">
<h3>Do you like PHP and AJAX so far?</h3>
<form>
Yes:
<input type="radio" name="vote" value="0" onclick="getVote(this.value)">
<br>No:
<input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>
</div>

</body>
</html>

The getVote() function does the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a file on the server
 Notice that a parameter (vote) is added to the URL (with the value of the yes or no option)

The PHP File


The page on the server called by the JavaScript above is a PHP file called "poll_vote.php":

<?php
$vote = $_REQUEST['vote'];

//get content of textfile


$filename = "poll_result.txt";
$content = file($filename);

//put content in array


$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0) {
$yes = $yes + 1;
}
if ($vote == 1) {
$no = $no + 1;
}

//insert votes to txt file


$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>

The value is sent from the JavaScript, and the following happens:

1. Get the content of the "poll_result.txt" file


2. Put the content of the file in variables and add one to the selected variable
3. Write the result to the "poll_result.txt" file
4. Output a graphical representation of the poll result

The Text File


The text file (poll_result.txt) is where we store the data from the poll.

It is stored like this:

0||0

The first number represents the "Yes" votes, the second number represents the "No" votes.

Note: Remember to allow your web server to edit the text file. Do NOT give everyone access,
just the web server (PHP).
PHP Reference

PHP libxml Functions

PHP libxml Introduction


The libxml functions and constants are used together with SimpleXML, XSLT and DOM
functions.

Installation
These functions require the libxml package. Download at xmlsoft.org

PHP libxml Functions


PHP: indicates the earliest version of PHP that supports the function.

Function Description

libxml_clear_errors() Clears the libxml error buffer

libxml_disable_entity_loader() Enables the ability to load external entities

libxml_get_errors() Gets the errors from the the libxml error buffer

libxml_get_last_error() Gets the last error from the the libxml error buffer

libxml_set_external_entity_loader() Changes the default external entity loader

Sets the streams context for the next libxml document load or
libxml_set_streams_context()
write

Disables the standard libxml errors and enables user error


libxml_use_internal_errors()
handling

PHP Predefined libxml Constants


Constant Description

LIBXML_BIGLINES Make line numbers greater than 65535 to be reported correctly

Set small nodes allocation optimization. This may improve the


LIBXML_COMPACT
application performance

LIBXML_DTDATTR Set default DTD attributes

LIBXML_DTDLOAD Load external subset

LIBXML_DTDVALID Validate with the DTD

LIBXML_HTML_NOIMPLIED Set HTML_PARSE_NOIMPLIED flag. This turns off automatic


adding of implied html/body elements

Set HTML_PARSE_NODEFDTD flag. This prevents a default


LIBXML_HTML_NODEFDTD
doctype to be added, if no doctype is found

LIBXML_NOBLANKS Remove blank nodes

LIBXML_NOCDATA Set CDATA as text nodes

Change empty tags (e.g. <br/> to <br></br>), only available in the


LIBXML_NOEMPTYTAG DOMDocument->save() and DOMDocument->saveXML()
functions

LIBXML_NOENT Substitute entities

LIBXML_NOERROR Do not show error reports

LIBXML_NONET Stop network access while loading documents

LIBXML_NOWARNING Do not show warning reports

LIBXML_NOXMLDECL Drop the XML declaration when saving a document

LIBXML_NSCLEAN Remove excess namespace declarations

Set XML_PARSE_HUGE flag. This relaxes any hardcoded limit from


LIBXML_PARSEHUGE the parser, such as maximum depth of a document or the size of
text nodes

Set XML_PARSE_PEDANTIC flag. This enables pedantic error


LIBXML_PEDANTIC
reporting

LIBXML_XINCLUDE Use XInclude substitution

LIBXML_ERR_ERROR Get recoverable errors

LIBXML_ERR_FATAL Get fatal errors

LIBXML_ERR_NONE Get no errors

LIBXML_ERR_WARNING Get simple warnings

LIBXML_VERSION Get libxml version (e.g. 20605 or 20617)

LIBXML_DOTTED_VERSION Get dotted libxml version (e.g. 2.6.5 or 2.6.17)

LIBXML_SCHEMA_CREATE Create default or fixed value nodes during XSD schema validation
PHP Mail Functions

PHP Mail Introduction


The mail() function allows you to send emails directly from a script.

Requirements
For the mail functions to be available, PHP requires an installed and working email system. The
program to be used is defined by the configuration settings in the php.ini file.

Installation
The mail functions are part of the PHP core. There is no installation needed to use these
functions.

Runtime Configuration
The behavior of the mail functions is affected by settings in php.ini:

Name Default Description Changeable

Add X-PHP-Originating-Script that will


mail.add_x_header "0" include UID of the script followed by the PHP_INI_PERDIR
filename. For PHP 5.3.0 and above

The path to a log file that will log all mail()


calls. Log include full path of script, line
mail.log NULL PHP_INI_PERDIR
number, To address and headers. For PHP
5.3.0 and above

Windows only: The DNS name or IP address


SMTP "localhost" PHP_INI_ALL
of the SMTP server

Windows only: The SMTP port number. For


smtp_port "25" PHP_INI_ALL
PHP 4.3.0 and above

Windows only: Specifies the "from" address


sendmail_from NULL PHP_INI_ALL
to be used when sending mail from mail()

Specifies where the sendmail program can


"/usr/sbin/sendmail be found. This directive works also under
sendmail_path PHP_INI_SYSTEM
-t -i" Windows. If set, SMTP, smtp_port and
sendmail_from are ignored

PHP Mail Functions


Function Description
ezmlm_hash() Calculates the hash value needed by EZMLM

mail() Allows you to send emails directly from a script


PHP Math Functions

PHP Math Introduction


The math functions can handle values within the range of integer and float types.

Installation
The PHP math functions are part of the PHP core. No installation is required to use these
functions.

PHP Math Functions


Function Description

abs() Returns the absolute (positive) value of a number

acos() Returns the arc cosine of a number

acosh() Returns the inverse hyperbolic cosine of a number

asin() Returns the arc sine of a number

asinh() Returns the inverse hyperbolic sine of a number

atan() Returns the arc tangent of a number in radians

atan2() Returns the arc tangent of two variables x and y

atanh() Returns the inverse hyperbolic tangent of a number

base_convert() Converts a number from one number base to another

bindec() Converts a binary number to a decimal number

ceil() Rounds a number up to the nearest integer

cos() Returns the cosine of a number

cosh() Returns the hyperbolic cosine of a number

decbin() Converts a decimal number to a binary number

dechex() Converts a decimal number to a hexadecimal number

decoct() Converts a decimal number to an octal number

deg2rad() Converts a degree value to a radian value

exp() Calculates the exponent of e

expm1() Returns exp(x) - 1


floor() Rounds a number down to the nearest integer

fmod() Returns the remainder of x/y

getrandmax() Returns the largest possible value returned by rand()

hexdec() Converts a hexadecimal number to a decimal number

hypot() Calculates the hypotenuse of a right-angle triangle

intdiv() Performs integer division

is_finite() Checks whether a value is finite or not

is_infinite() Checks whether a value is infinite or not

is_nan() Checks whether a value is 'not-a-number'

lcg_value() Returns a pseudo random number in a range between 0 and 1

log() Returns the natural logarithm of a number

log10() Returns the base-10 logarithm of a number

log1p() Returns log(1+number)

Returns the highest value in an array, or the highest value of several specified
max()
values

Returns the lowest value in an array, or the lowest value of several specified
min()
values

mt_getrandmax() Returns the largest possible value returned by mt_rand()

mt_rand() Generates a random integer using Mersenne Twister algorithm

mt_srand() Seeds the Mersenne Twister random number generator

octdec() Converts an octal number to a decimal number

pi() Returns the value of PI

pow() Returns x raised to the power of y

rad2deg() Converts a radian value to a degree value

rand() Generates a random integer

round() Rounds a floating-point number

sin() Returns the sine of a number

sinh() Returns the hyperbolic sine of a number

sqrt() Returns the square root of a number

srand() Seeds the random number generator

tan() Returns the tangent of a number

tanh() Returns the hyperbolic tangent of a number


PHP Predefined Math Constants
Constant Value Description

INF INF The infinite

M_E 2.7182818284590452354 Returns e

M_EULER 0.57721566490153286061 Returns Euler constant

M_LNPI 1.14472988584940017414 Returns the natural logarithm of PI: log_e(pi)

M_LN2 0.69314718055994530942 Returns the natural logarithm of 2: log_e 2

M_LN10 2.30258509299404568402 Returns the natural logarithm of 10: log_e 10

M_LOG2E 1.4426950408889634074 Returns the base-2 logarithm of E: log_2 e

M_LOG10E 0.43429448190325182765 Returns the base-10 logarithm of E: log_10 e

M_PI 3.14159265358979323846 Returns Pi

M_PI_2 1.57079632679489661923 Returns Pi/2

M_PI_4 0.78539816339744830962 Returns Pi/4

M_1_PI 0.31830988618379067154 Returns 1/Pi

M_2_PI 0.63661977236758134308 Returns 2/Pi

M_SQRTPI 1.77245385090551602729 Returns the square root of PI: sqrt(pi)

M_2_SQRTPI 1.12837916709551257390 Returns 2/square root of PI: 2/sqrt(pi)

M_SQRT1_2 0.70710678118654752440 Returns the square root of 1/2: 1/sqrt(2)

M_SQRT2 1.41421356237309504880 Returns the square root of 2: sqrt(2)

M_SQRT3 1.73205080756887729352 Returns the square root of 3: sqrt(3)

NAN NAN Not A Number

PHP_ROUND_HALF_UP 1 Round halves up

PHP_ROUND_HALF_DOWN 2 Round halves down

PHP_ROUND_HALF_EVEN 3 Round halves to even numbers

PHP_ROUND_HALF_ODD 4 Round halves to odd numbers


PHP Misc. Functions

PHP Miscellaneous Introduction


The misc. functions were only placed here because none of the other categories seemed to fit.

Installation
The misc. functions are part of the PHP core. No installation is required to use these functions.

Runtime Configuration
The behavior of the misc. functions is affected by settings in the php.ini file.

Misc. configuration options:

Name Description Default Changeable

FALSE indicates that scripts will be terminated


ignore_user_abort as soon as they try to output something after a "0" PHP_INI_ALL
client has aborted their connection

highlight.string Color for highlighting a string in PHP syntax "#DD0000" PHP_INI_ALL

highlight.comment Color for highlighting PHP comments "#FF8000" PHP_INI_ALL

Color for syntax highlighting PHP keywords


highlight.keyword "#007700" PHP_INI_ALL
(e.g. parenthesis and semicolon)

highlight.default Default color for PHP syntax "#0000BB" PHP_INI_ALL

highlight.html Color for HTML code "#000000" PHP_INI_ALL

Name and location of browser-capabilities file


browscap NULL PHP_INI_SYSTEM
(e.g. browscap.ini)

PHP Miscellaneous Functions


Function Description

connection_aborted() Checks whether the client has disconnected

connection_status() Returns the current connection status

Deprecated from PHP 4.0.5. Checks whether the script has timed
connection_timeout()
out

constant() Returns the value of a constant


define() Defines a constant

defined() Checks whether a constant exists

die() Alias of exit()

eval() Evaluates a string as PHP code

exit() Prints a message and exits the current script

get_browser() Returns the capabilities of the user's browser

__halt_compiler() Halts the compiler execution

highlight_file() Outputs a file with the PHP syntax highlighted

highlight_string() Outputs a string with the PHP syntax highlighted

hrtime() Returns the system's high resolution time

ignore_user_abort() Sets whether a remote client can abort the running of a script

pack() Packs data into a binary string

Returns the source code of a file with PHP comments and


php_strip_whitespace()
whitespace removed

show_source() Alias of highlight_file()

sleep() Delays code execution for a number of seconds

sys_getloadavg() Returns the system load average

time_nanosleep() Delays code execution for a number of seconds and nanoseconds

time_sleep_until() Makes a script sleep until the specified time

uniqid() Generates a unique ID

unpack() Unpacks data from a binary string

usleep() Delays code execution for a number of microseconds

PHP Predefined Misc. Constants


Constant Description

CONNECTION_ABORTED Connection is aborted by user or network error

CONNECTION_NORMAL Connection is running normally

CONNECTION_TIMEOUT Connection timed out

__COMPILER_HALT_OFFSET__
PHP MySQLi Functions

PHP MySQLi Introduction


The MySQLi functions allows you to access MySQL database servers.

Note: The MySQLi extension is designed to work with MySQL version 4.1.13 or newer.

Installation / Runtime Configuration


For the MySQLi functions to be available, you must compile PHP with support for the MySQLi
extension.

The MySQLi extension was introduced with PHP version 5.0.0. The MySQL Native Driver was
included in PHP version 5.3.0.

For installation details, go to: http://php.net/manual/en/mysqli.installation.php

For runtime configuration details, go to: http://php.net/manual/en/mysqli.configuration.php

PHP MySQLi Functions


Function Description

affected_rows() Returns the number of affected rows in the previous MySQL operation

autocommit() Turns on or off auto-committing database modifications

begin_transaction() Starts a transaction

change_user() Changes the user of the specified database connection

character_set_name() Returns the default character set for the database connection

close() Closes a previously opened database connection

commit() Commits the current transaction

connect() Opens a new connection to the MySQL server

connect_errno() Returns the error code from the last connection error

connect_error() Returns the error description from the last connection error

data_seek() Adjusts the result pointer to an arbitrary row in the result-set

debug() Performs debugging operations

dump_debug_info() Dumps debugging info into the log

errno() Returns the last error code for the most recent function call

error() Returns the last error description for the most recent function call
error_list() Returns a list of errors for the most recent function call

fetch_all() Fetches all result rows as an associative array, a numeric array, or both

fetch_array() Fetches a result row as an associative, a numeric array, or both

fetch_assoc() Fetches a result row as an associative array

fetch_field() Returns the next field in the result-set, as an object

fetch_field_direct() Returns meta-data for a single field in the result-set, as an object

fetch_fields() Returns an array of objects that represent the fields in a result-set

fetch_lengths() Returns the lengths of the columns of the current row in the result-set

fetch_object() Returns the current row of a result-set, as an object

fetch_row() Fetches one row from a result-set and returns it as an enumerated array

field_count() Returns the number of columns for the most recent query

field_seek() Sets the field cursor to the given field offset

get_charset() Returns a character set object

get_client_info() Returns the MySQL client library version

get_client_stats() Returns statistics about client per-process

get_client_version() Returns the MySQL client library version as an integer

get_connection_stats() Returns statistics about the client connection

get_host_info() Returns the MySQL server hostname and the connection type

get_proto_info() Returns the MySQL protocol version

get_server_info() Returns the MySQL server version

get_server_version() Returns the MySQL server version as an integer

info() Returns information about the last executed query

init() Initializes MySQLi and returns a resource for use with real_connect()

insert_id() Returns the auto-generated id from the last query

kill() Asks the server to kill a MySQL thread

more_results() Checks if there are more results from a multi query

multi_query() Performs one or more queries on the database

next_result() Prepares the next result-set from multi_query()

options() Sets extra connect options and affect behavior for a connection

Pings a server connection, or tries to reconnect if the connection has


ping()
gone down
poll() Polls connections

prepare() Prepares an SQL statement for execution

query() Performs a query against a database

real_connect() Opens a new connection to the MySQL server

real_escape_string() Escapes special characters in a string for use in an SQL statement

real_query() Executes a single SQL query

reap_async_query() Returns result from an async SQL query

Refreshes/flushes tables or caches, or resets the replication server


refresh()
information

rollback() Rolls back the current transaction for the database

select_db() Select the default database for database queries

set_charset() Sets the default client character set

set_local_infile_default() Unsets user defined handler for load local infile command

set_local_infile_handler() Set callback function for LOAD DATA LOCAL INFILE command

sqlstate() Returns the SQLSTATE error code for the error

ssl_set() Used to establish secure connections using SSL

stat() Returns the current system status

stmt_init() Initializes a statement and returns an object for use with stmt_prepare()

store_result() Transfers a result-set from the last query

thread_id() Returns the thread ID for the current connection

thread_safe() Returns whether the client library is compiled as thread-safe

use_result() Initiates the retrieval of a result-set from the last query executed

warning_count() Returns the number of warnings from the last query in the connection
PHP Network Functions

PHP Network Introduction


The Network functions contains various network function and let you manipulate information
sent to the browser by the Web server, before any other output has been sent.

Installation
The Network functions are part of the PHP core. There is no installation needed to use these
functions.

PHP Network Functions


Function Description

checkdnsrr() Checks DNS records for type corresponding to host

closelog() Closes the connection of system logger

Deprecated and removed in PHP 5.4. Initializes the variables used in


define_syslog_variables()
syslog functions

dns_check_record() Alias of checkdnsrr()

dns_get_mx() Alias of getmxrr()

dns_get_record() Gets the DNS resource records associated with the specified hostname

fsockopen() Opens an Internet or Unix domain socket connection

gethostbyaddr() Returns the domain name for a given IP address

gethostbyname() Returns the IPv4 address for a given domain/host name

gethostbynamel() Returns a list of IPv4 address for a given domain/host name

gethostname() Returns the host name

getmxrr() Returns the MX records for the specified internet host name

getprotobyname() Returns the protocol number for a given protocol name

getprotobynumber() Returns the protocol name for a given protocol number

getservbyname() Returns the port number for a given Internet service and protocol

getservbyport() Returns the Internet service for a given port and protocol

header_register_callback() Calls a header function

header_remove() Removes an HTTP header previously set with the header() function
header() Sends a raw HTTP header to a client

headers_list() Returns a list of response headers to be sent to the browser

headers_sent() Checks if/where headers have been sent

http_response_code() Sets or returns the HTTP response status code

inet_ntop() Converts a 32bit IPv4 or 128bit IPv6 address into a readable format

Converts a readable IP address into a packed 32bit IPv4 or 128bit IPv6


inet_pton()
format

ip2long() Converts an IPv4 address into a long integer

long2ip() Converts a long integer address into a string in IPv4 format

openlog() Opens the connection of system logger

pfsockopen() Opens a persistent Internet or Unix domain socket connection

setcookie() Defines a cookie to be sent along with the rest of the HTTP headers

Defines a cookie (without URL encoding) to be sent along with the rest
setrawcookie()
of the HTTP headers

socket_get_status() Alias of stream_get_meta_data()

socket_set_blocking() Alias of stream_set_blocking()

socket_set_timeout() Alias of stream_set_timeout()

syslog() Generates a system log message


PHP SimpleXML Functions

PHP SimpleXML Introduction


SimpleXML is an extension that allows us to easily manipulate and get XML data.

SimpleXML provides an easy way of getting an element's name, attributes and textual content if
you know the XML document's structure or layout.

SimpleXML turns an XML document into a data structure you can iterate through like a
collection of arrays and objects.

Installation
From PHP 5, the SimpleXML functions are part of the PHP core. No installation is required to
use these functions.

PHP SimpleXML Functions


Function Description

__construct() Creates a new SimpleXMLElement object

__toString() Returns the string content of an element

addAttribute() Appends an attribute to the SimpleXML element

addChild() Appends a child element the SimpleXML element

Returns a well-formed XML string (XML version 1.0) from a SimpleXML


asXML()
object

attributes() Returns the attributes/values of an element

children() Returns the children of a specified node

count() Counts the children of a specified node

getDocNamespaces() Returns the namespaces declared in document

getName() Returns the name of an element

getNamespaces() Returns the namespaces used in document

registerXPathNamespace() Creates a namespace context for the next XPath query

saveXML() Alias of asXML()

simplexml_import_dom() Returns a SimpleXMLElement object from a DOM node

simplexml_load_file() Converts an XML document to an object

simplexml_load_string() Converts an XML string to an object


xpath() Runs an XPath query on XML data

PHP SimpleXML Iteration Functions


Function Description

current() Returns the current element

getChildren() Returns the child elements of the current element

hasChildren() Checks whether the current element has children

key() Returns the XML tag name of the current element

next() Moves to the next element

rewind() Rewinds to the first element

valid() Checks whether the current element is valid


PHP Stream Functions

PHP Stream Introduction


The Stream functions ....

Streams are the way of generalizing file, network, data compression, and other operations which
share a common set of functions and uses. In its simplest definition, a stream is a resource object
which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion,
and may be able to fseek() to an arbitrary location within the stream.
A wrapper is additional code which tells the stream how to handle specific protocols/encodings.

Installation
The Stream functions are part of the PHP core. There is no installation needed to use these
functions.

PHP Stream Functions


Function Description

Deprecated in PHP 5.4, and removed in PHP 7.0. Alias of


set_socket_blocking()
stream_set_blocking()

stream_bucket_prepend()

stream_context_create()

stream_context_get_default()

stream_context_get_options()

stream_context_get_params()

stream_context_set_default()

stream_context_set_options()

stream_context_set_params()

stream_copy_to_stream() Copies data from one stream to another

stream_filter_append() Appends a filter to a stream

stream_filter_prepend()

stream_filter_register()

stream_filter_remove()

stream_get_contents()

stream_get_filters()
stream_get_line()

stream_get_meta_data()

stream_get_transports()

stream_get_wrappers()

stream_is_local()

stream_isatty()

stream_notification_callback()

stream_register_wrapper() Alias of stream_wrapper_register()

stream_resolve_include_path()

stream_select()

stream_set_blocking()

stream_set_chunk_size()

stream_set_read_buffer()

stream_set_timeout()

stream_set_write_buffer()

stream_socket_accept()

stream_socket_client()

stream_socket_enable_crypto()

stream_socket_get_name()

stream_socket_pair()

stream_socket_recvfrom()

stream_socket_sendto()

stream_socket_server()

stream_socket_shutdown()

stream_supports_lock()

stream_wrapper_register()

stream_wrapper_restore()

stream_wrapper_unregister()
PHP String Functions

PHP String Functions


The PHP string functions are part of the PHP core. No installation is required to use these
functions.

Function Description

addcslashes() Returns a string with backslashes in front of the specified characters

addslashes() Returns a string with backslashes in front of predefined characters

bin2hex() Converts a string of ASCII characters to hexadecimal values

chop() Removes whitespace or other characters from the right end of a string

chr() Returns a character from a specified ASCII value

chunk_split() Splits a string into a series of smaller parts

convert_cyr_string() Converts a string from one Cyrillic character-set to another

convert_uudecode() Decodes a uuencoded string

convert_uuencode() Encodes a string using the uuencode algorithm

count_chars() Returns information about characters used in a string

crc32() Calculates a 32-bit CRC for a string

crypt() One-way string hashing

echo() Outputs one or more strings

explode() Breaks a string into an array

fprintf() Writes a formatted string to a specified output stream

Returns the translation table used by htmlspecialchars() and


get_html_translation_table()
htmlentities()

hebrev() Converts Hebrew text to visual text

hebrevc() Converts Hebrew text to visual text and new lines (\n) into <br>

hex2bin() Converts a string of hexadecimal values to ASCII characters

html_entity_decode() Converts HTML entities to characters

htmlentities() Converts characters to HTML entities

htmlspecialchars_decode() Converts some predefined HTML entities to characters

htmlspecialchars() Converts some predefined characters to HTML entities

implode() Returns a string from the elements of an array


join() Alias of implode()

lcfirst() Converts the first character of a string to lowercase

levenshtein() Returns the Levenshtein distance between two strings

localeconv() Returns locale numeric and monetary formatting information

ltrim() Removes whitespace or other characters from the left side of a string

md5() Calculates the MD5 hash of a string

md5_file() Calculates the MD5 hash of a file

metaphone() Calculates the metaphone key of a string

money_format() Returns a string formatted as a currency string

nl_langinfo() Returns specific local information

nl2br() Inserts HTML line breaks in front of each newline in a string

number_format() Formats a number with grouped thousands

ord() Returns the ASCII value of the first character of a string

parse_str() Parses a query string into variables

print() Outputs one or more strings

printf() Outputs a formatted string

quoted_printable_decode() Converts a quoted-printable string to an 8-bit string

quoted_printable_encode() Converts an 8-bit string to a quoted printable string

quotemeta() Quotes meta characters

rtrim() Removes whitespace or other characters from the right side of a string

setlocale() Sets locale information

sha1() Calculates the SHA-1 hash of a string

sha1_file() Calculates the SHA-1 hash of a file

similar_text() Calculates the similarity between two strings

soundex() Calculates the soundex key of a string

sprintf() Writes a formatted string to a variable

sscanf() Parses input from a string according to a format

str_getcsv() Parses a CSV string into an array

str_ireplace() Replaces some characters in a string (case-insensitive)

str_pad() Pads a string to a new length

str_repeat() Repeats a string a specified number of times


str_replace() Replaces some characters in a string (case-sensitive)

str_rot13() Performs the ROT13 encoding on a string

str_shuffle() Randomly shuffles all characters in a string

str_split() Splits a string into an array

str_word_count() Count the number of words in a string

strcasecmp() Compares two strings (case-insensitive)

Finds the first occurrence of a string inside another string (alias of


strchr()
strstr())

strcmp() Compares two strings (case-sensitive)

strcoll() Compares two strings (locale based string comparison)

Returns the number of characters found in a string before any part of


strcspn()
some specified characters are found

strip_tags() Strips HTML and PHP tags from a string

stripcslashes() Unquotes a string quoted with addcslashes()

stripslashes() Unquotes a string quoted with addslashes()

Returns the position of the first occurrence of a string inside another


stripos()
string (case-insensitive)

Finds the first occurrence of a string inside another string (case-


stristr()
insensitive)

strlen() Returns the length of a string

strnatcasecmp() Compares two strings using a "natural order" algorithm (case-insensitive)

strnatcmp() Compares two strings using a "natural order" algorithm (case-sensitive)

strncasecmp() String comparison of the first n characters (case-insensitive)

strncmp() String comparison of the first n characters (case-sensitive)

strpbrk() Searches a string for any of a set of characters

Returns the position of the first occurrence of a string inside another


strpos()
string (case-sensitive)

strrchr() Finds the last occurrence of a string inside another string

strrev() Reverses a string

Finds the position of the last occurrence of a string inside another string
strripos()
(case-insensitive)

Finds the position of the last occurrence of a string inside another string
strrpos()
(case-sensitive)

Returns the number of characters found in a string that contains only


strspn()
characters from a specified charlist
strstr() Finds the first occurrence of a string inside another string (case-sensitive)

strtok() Splits a string into smaller strings

strtolower() Converts a string to lowercase letters

strtoupper() Converts a string to uppercase letters

strtr() Translates certain characters in a string

substr() Returns a part of a string

Compares two strings from a specified start position (binary safe and
substr_compare()
optionally case-sensitive)

substr_count() Counts the number of times a substring occurs in a string

substr_replace() Replaces a part of a string with another string

trim() Removes whitespace or other characters from both sides of a string

ucfirst() Converts the first character of a string to uppercase

ucwords() Converts the first character of each word in a string to uppercase

vfprintf() Writes a formatted string to a specified output stream

vprintf() Outputs a formatted string

vsprintf() Writes a formatted string to a variable

wordwrap() Wraps a string to a given number of characters


PHP Variable Handling Functions

PHP Variable Handling Functions


The PHP variable handling functions are part of the PHP core. No installation is required to use
these functions.

Function Description

boolval() Returns the boolean value of a variable

debug_zval_dump() Dumps a string representation of an internal zend value to output

doubleval() Alias of floatval()

empty() Checks whether a variable is empty

floatval() Returns the float value of a variable

get_defined_vars() Returns all defined variables, as an array

get_resource_type() Returns the type of a resource

gettype() Returns the type of a variable

intval() Returns the integer value of a variable

is_array() Checks whether a variable is an array

is_bool() Checks whether a variable is a boolean

is_callable() Checks whether the contents of a variable can be called as a function

is_countable() Checks whether the contents of a variable is a countable value

is_double() Alias of is_float()

is_float() Checks whether a variable is of type float

is_int() Checks whether a variable is of type integer

is_integer() Alias of is_int()

is_iterable() Checks whether the contents of a variable is an iterable value

is_long() Alias of is_int()

is_null() Checks whether a variable is NULL

is_numeric() Checks whether a variable is a number or a numeric string

is_object() Checks whether a variable is an object

is_real() Alias of is_float()

is_resource() Checks whether a variable is a resource

is_scalar() Checks whether a variable is a scalar


is_string() Checks whether a variable is of type string

isset() Checks whether a variable is set (declared and not NULL)

print_r() Prints the information about a variable in a human-readable way

serialize() Converts a storable representation of a value

settype() Converts a variable to a specific type

strval() Returns the string value of a variable

unserialize() Converts serialized data back into actual data

unset() Unsets a variable

var_dump() Dumps information about one or more variables

var_export() Returns structured information (valid PHP code) about a variable


PHP XML Parser Functions

PHP XML Parser Introduction


The XML functions lets you parse, but not validate, XML documents.

XML is a data format for standardized structured document exchange. More information on
XML can be found in our XML Tutorial.

This extension uses the Expat XML parser.

Expat is an event-based parser, it views an XML document as a series of events. When an event
occurs, it calls a specified function to handle it.

Expat is a non-validating parser, and ignores any DTDs linked to a document. However, if the
document is not well formed it will end with an error message.

Because it is an event-based, non validating parser, Expat is fast and well suited for web
applications.

The XML parser functions lets you create XML parsers and define handlers for XML events.

Installation
The XML functions are part of the PHP core. There is no installation needed to use these
functions.

PHP XML Parser Functions


Function Description

utf8_decode() Decodes an UTF-8 string to ISO-8859-1

utf8_encode() Encodes an ISO-8859-1 string to UTF-8

xml_error_string() Returns an error string from the XML parser

xml_get_current_byte_index() Returns the current byte index from the XML parser

Returns the current column number from the XML


xml_get_current_column_number()
parser

xml_get_current_line_number() Returns the current line number from the XML parser

xml_get_error_code() Returns an error code from the XML parser

xml_parse() Parses an XML document

xml_parse_into_struct() Parses XML data into an array

xml_parser_create_ns() Creates an XML parser with namespace support

xml_parser_create() Creates an XML parser


xml_parser_free() Frees an XML parser

xml_parser_get_option() Returns options from an XML parser

xml_parser_set_option() Sets options in an XML parser

xml_set_character_data_handler() Sets up the character data handler for the XML parser

xml_set_default_handler() Sets up the default data handler for the XML parser

Sets up start and end element handlers for the XML


xml_set_element_handler()
parser

xml_set_end_namespace_decl_handler() Sets up the end namespace declaration handler

Sets up the external entity reference handler for the


xml_set_external_entity_ref_handler()
XML parser

xml_set_notation_decl_handler() Sets up notation declaration handler for the XML parser

xml_set_object() Allows to use XML parser within an object

xml_set_processing_instruction_handler() Sets up processing instruction handler

xml_set_start_namespace_decl_handler() Sets up the start namespace declaration handler

xml_set_unparsed_entity_decl_handler() Sets handler function for unparsed entity declarations

PHP XML Parser Constants


Constant

XML_ERROR_NONE (integer)

XML_ERROR_NO_MEMORY (integer)

XML_ERROR_SYNTAX (integer)

XML_ERROR_NO_ELEMENTS (integer)

XML_ERROR_INVALID_TOKEN (integer)

XML_ERROR_UNCLOSED_TOKEN (integer)

XML_ERROR_PARTIAL_CHAR (integer)

XML_ERROR_TAG_MISMATCH (integer)

XML_ERROR_DUPLICATE_ATTRIBUTE (integer)

XML_ERROR_JUNK_AFTER_DOC_ELEMENT (integer)

XML_ERROR_PARAM_ENTITY_REF (integer)

XML_ERROR_UNDEFINED_ENTITY (integer)

XML_ERROR_RECURSIVE_ENTITY_REF (integer)
XML_ERROR_ASYNC_ENTITY (integer)

XML_ERROR_BAD_CHAR_REF (integer)

XML_ERROR_BINARY_ENTITY_REF (integer)

XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF (integer)

XML_ERROR_MISPLACED_XML_PI (integer)

XML_ERROR_UNKNOWN_ENCODING (integer)

XML_ERROR_INCORRECT_ENCODING (integer)

XML_ERROR_UNCLOSED_CDATA_SECTION (integer)

XML_ERROR_EXTERNAL_ENTITY_HANDLING (integer)

XML_OPTION_CASE_FOLDING (integer)

XML_OPTION_TARGET_ENCODING (integer)

XML_OPTION_SKIP_TAGSTART (integer)

XML_OPTION_SKIP_WHITE (integer)

XML_SAX_IMPL (string)
PHP Zip Functions

PHP Zip Introduction


The Zip files functions allows you to read ZIP files.

Requirements
The ZIP extension requires libzip.

Installation
Linux Systems

For these functions to work, you have to compile PHP with --enable-zip.

PHP 5.6: Use the --with-libzip=DIR configure option to use a system libzip installation. libzip
version 0.11 is required, with 0.11.2 or later recommended.

PHP 7.3: Building against the bundled libzip is discouraged, but still possible by adding --
without-libzip to the configuration.

Windows Systems

Before PHP 5.3: Users must enable "php_zip.dll" inside of "php.ini" for these functions to work.

From PHP 5.3: The ZIP extension is built-in.

PHP Zip Functions


Function Description

zip_close() Closes a ZIP file archive

zip_entry_close() Closes a ZIP directory entry

zip_entry_compressedsize() Returns the compressed file size of a ZIP directory entry

zip_entry_compressionmethod() Returns the compression method of a ZIP directory entry

zip_entry_filesize() Returns the actual file size of a ZIP directory entry

zip_entry_name() Returns the name of a ZIP directory entry

zip_entry_open() Opens a directory entry in a ZIP file for reading

zip_entry_read() Reads from an open directory entry in the ZIP file

zip_open() Opens a ZIP file archive

zip_read() Reads the next file in a open ZIP file archive


PHP Timezones

PHP Supported Timezones


Below is a complete list of the timezones supported by PHP, which are useful with several PHP
date functions.

 Africa
 America
 Antarctica
 Arctic
 Asia
 Atlantic
 Australia
 Europe
 Indian
 Pacific

Indian
Indian/Antananarivo Indian/Chagos Indian/Christmas Indian/Cocos Indian/Comoro
Indian/Kerguelen Indian/Mahe Indian/Maldives Indian/Mauritius Indian/Mayotte
Indian/Reunion

You might also like