PHP Tutorial - W3schools2 PDF
PHP Tutorial - W3schools2 PDF
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
Database Queries
A query is a question or a request.
We can query a database for specific information and have a recordset returned.
The query above selects all the data in the "LastName" column from the "Employees" table.
Another great thing about MySQL is that it can be scaled down to support embedded database
applications.
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
<?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";
?>
$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());
}
<?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.
MySQLi Object-Oriented:
$conn->close();
MySQLi Procedural:
mysqli_close($conn);
PDO:
$conn = null;
PHP Create a MySQL Database
You will need special CREATE privileges to create or to delete a MySQL database.
<?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)
<?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);
?>
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.
We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname",
"email" and "reg_date":
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.
<?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);
}
$conn->close();
?>
<?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());
}
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);
$conn = null;
?>
PHP MySQL Insert Data
The INSERT INTO statement is used to add new records to a MySQL table:
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.
<?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);
}
$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());
}
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
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:
<?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);
}
$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());
}
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);
}
$conn->close();
?>
Note that each SQL statement must be separated by a semicolon.
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
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);
$conn = null;
?>
PHP MySQL Prepared Statements
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.
<?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);
}
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
$stmt->close();
$conn->close();
?>
In our SQL, we insert a question mark (?) where we want to substitute in an integer, string,
double or blob value.
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.
i - integer
d - double
s - string
b - BLOB
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:
<?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);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
<?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);
}
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:
<?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());
}
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
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
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>";
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();
Output
Id Firstname Lastname
1 John Doe
2 Mary Moe
3 Julie Dooley
PHP MySQL Use The WHERE Clause
The WHERE clause is used to extract only those records that fulfill a specified condition.
<!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);
}
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
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:
<!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());
}
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:
<!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);
}
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>";
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();
</body>
</html>
PHP MySQL Use The ORDER BY Clause
<!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);
}
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>
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:
<!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());
}
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>
<!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);
}
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>
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>";
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();
</body>
</html>
PHP MySQL Delete Data
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!
The following examples delete the record with id=3 in the "MyGuests" table:
<?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);
}
$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());
}
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);
$conn = null;
?>
After the record is deleted, the table will look like this:
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!
The following examples update the record with id=2 in the "MyGuests" table:
<?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);
}
$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());
}
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);
// Prepare statement
$stmt = $conn->prepare($sql);
$conn = null;
?>
After the record is updated, the table will look like this:
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:
When the SQL query above is run, it will return the first 30 records.
The SQL query below says "return only 10 records, start on record 16 (OFFSET 15)":
You could also use a shorter syntax to achieve the same result:
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.
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.
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.
XMLReader
XML Expat Parser
PHP SimpleXML Parser
SimpleXML is a PHP extension that allows us to easily manipulate and get XML data.
Installation
From PHP 5, the SimpleXML functions are part of the PHP core. No installation is required to
use these functions.
The example below shows how to use the simplexml_load_string() function to read XML
data from a string:
Example
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);
}
?>
Assume we have an XML file called "note.xml", that looks like this:
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!
SimpleXML is a PHP extension that allows us to easily manipulate and get XML data.
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;
?>
Tove
Jani
Reminder
Don't forget me this weekend!
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;
?>
Everyday Italian
Harry Potter
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>";
}
?>
<?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'];
?>
COOKING
en
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.
<from>Jani</from>
The XML Expat Parser functions are part of the PHP core. There is no installation needed to use
these functions.
Example
<?php
// Initialize the XML parser
$parser=xml_parser_create();
// 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)));
}
Output
-- Note --
To: Tove
From: Jani
Heading: Reminder
Message: Don't forget me this weekend!
Example explained:
The built-in DOM parser makes it possible to process XML documents in PHP.
Installation
The DOM parser functions are part of the PHP core. There is no installation needed to use these
functions.
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
print $xmlDoc->saveXML();
?>
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.
<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("note.xml");
$x = $xmlDoc->documentElement;
foreach ($x->childNodes AS $item) {
print $item->nodeName . " = " . $item->nodeValue . "<br>";
}
?>
#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
AJAX is about updating parts of a web page, without reloading the whole page.
What is AJAX?
AJAX = Asynchronous JavaScript and XML.
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.
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.
If you want to learn more about AJAX, visit our AJAX tutorial.
Example Explained
In the example above, when a user types a character in the input field, a function called
"showHint()" is executed.
<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>
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.
$hint = "";
Example Explained
In the example above, when a user selects a person in the dropdown list above, a function called
"showUser()" is executed.
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:
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:
<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>
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 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"];
$x=$xmlDoc->getElementsByTagName('ARTIST');
$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:
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.
<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>
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:
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');
Ouput
If there is any text sent from the JavaScript (strlen($q) > 0), the following happens:
AJAX Poll
The following example will demonstrate a poll where the result is shown without reloading.
Yes:
No:
<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>
<?php
$vote = $_REQUEST['vote'];
if ($vote == 0) {
$yes = $yes + 1;
}
if ($vote == 1) {
$no = $no + 1;
}
<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:
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
Installation
These functions require the libxml package. Download at xmlsoft.org
Function Description
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
Sets the streams context for the next libxml document load or
libxml_set_streams_context()
write
LIBXML_SCHEMA_CREATE Create default or fixed value nodes during XSD schema validation
PHP Mail Functions
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:
Installation
The PHP math functions are part of the PHP core. No installation is required to use these
functions.
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
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.
Deprecated from PHP 4.0.5. Checks whether the script has timed
connection_timeout()
out
ignore_user_abort() Sets whether a remote client can abort the running of a script
__COMPILER_HALT_OFFSET__
PHP MySQLi Functions
Note: The MySQLi extension is designed to work with MySQL version 4.1.13 or newer.
The MySQLi extension was introduced with PHP version 5.0.0. The MySQL Native Driver was
included in PHP version 5.3.0.
affected_rows() Returns the number of affected rows in the previous MySQL operation
character_set_name() Returns the default character set for the database connection
connect_errno() Returns the error code from the last connection error
connect_error() Returns the error description from the last connection error
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_lengths() Returns the lengths of the columns of the current row in the result-set
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
get_host_info() Returns the MySQL server hostname and the connection type
init() Initializes MySQLi and returns a resource for use with real_connect()
options() Sets extra connect options and affect behavior for a connection
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
stmt_init() Initializes a statement and returns an object for use with stmt_prepare()
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
Installation
The Network functions are part of the PHP core. There is no installation needed to use these
functions.
dns_get_record() Gets the DNS resource records associated with the specified hostname
getmxrr() Returns the MX records for the specified internet host name
getservbyname() Returns the port number for a given Internet service and protocol
getservbyport() Returns the Internet service for a given port and protocol
header_remove() Removes an HTTP header previously set with the header() function
header() Sends a raw HTTP header to a client
inet_ntop() Converts a 32bit IPv4 or 128bit IPv6 address into a readable format
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
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.
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.
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_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_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
Function Description
chop() Removes whitespace or other characters from the right end of a string
hebrevc() Converts Hebrew text to visual text and new lines (\n) into <br>
ltrim() Removes whitespace or other characters from the left side of a string
rtrim() Removes whitespace or other characters from the right side of 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)
Compares two strings from a specified start position (binary safe and
substr_compare()
optionally case-sensitive)
Function Description
XML is a data format for standardized structured document exchange. More information on
XML can be found in our XML Tutorial.
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.
xml_get_current_byte_index() Returns the current byte index from the XML parser
xml_get_current_line_number() Returns the current line number from the 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
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
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.
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