Unit 4 - PHP 0 Mysql Notes
Unit 4 - PHP 0 Mysql Notes
With PHP, you can connect to and manipulate databases.MySQL is the most popular database
system used with PHP.
What is MySQL?
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 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):
The query above selects all the data in the "LastName" column from the "Employees" table.
If you don't have a PHP server with a MySQL Database, you can download it for free
here: http://www.mysql.com
PHP Connect to MySQL
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in
2012.
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.
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.
PDO Installation
Before we can access data in the MySQL database, we need to be able to connect to the server:
// 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.
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;
A database consists of one or more tables.You will need special CREATE privileges to create or
to delete a MySQL database.
// 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);
?>
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.
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":
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 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.
// 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 "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
Insert Data Into MySQL Using MySQLi and PDO. After a database and a table have been created,
we can start adding data in them.
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.
Financial Assistance to students under EWS Scheme of university for the year 2023-2024
// 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
Get ID of The Last Inserted Record
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:
// 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
The following examples add three new records to the "MyGuests" table:
// 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.
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_multi_query($conn, $sql)) {
echo "New records 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);
$conn = null;
?>
PHP MySQL Prepared Statements
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly
with high efficiency.
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:
// 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();
?>
Code lines to explain from the example above:
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
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:
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();
The SELECT statement is used to select data from one or more tables:
The following example selects the id, firstname and lastname columns from the MyGuests table
and displays it on the page:
Example (MySQLi Object-oriented)Get your own PHP Server
<?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();
?>
Run example »
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:
// 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);
?>
Run example »
// 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();
?>
Run example »
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();
The WHERE clause is used to extract only those records that fulfill a specified condition.
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:
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();
?>
Run example »
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:
// 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);
?>
Run example »
// 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();
?>
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)
<?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();
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.
The following example selects the id, firstname and lastname columns from the MyGuests table.
The records will be ordered by the lastname column:
// 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();
?>
Run example »
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:
// 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);
?>
// 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();
?>
Select Data With PDO (+ 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)
<?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();
// 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>";
?>
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!
The following examples delete the record with id=3 in the "MyGuests" table:
// 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:
// 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";
$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:
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.
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.
Basics of phpMyAdmin
•
As •we know that, any simple website or application needs interaction with data or data
management, so it uses databases phpMyAdmin has become one of the popular, free, open-source
software platform for administration of MySQL and MariaDB data over the web world. This tool
is primarily written in PHP for web hosting and related services.
This GUI tool manages a lot of data related operations such as creation, modification, deletion of
data, change structure of table which are in the Databases. It can manage multiple databases at a
time. It also performs other actions like browsing data, executing SQL queries along with
managing indexes, users, and permissions. This also provides functionality like taking backups,
doing search operations, import and export of data in different formats like SQL, CSV, XML,
Excel sheets.
phpMyAdmin is the most trusted and user-friendly database managers and mostly used for web-
based applications or programs. In the following article, we will be learning about the importance
of the phpMyAdmin tool in the web world.
phpMyAdmin | Pre-requisites: To install phpMyAdmin software, you need a server running
platform like Windows or Linux supports operating systems.
• Web Browser: You need a web browser interface to run the tool.
• PHP scripting language: You need a server side language.
• Apache Web server: You need a web server to store phpMyAdmin files.
• MySQL or MariaDB Database: You need a database to manage application data.
Note: XAMPP package installation is the easiest way to get phpMyAdmin tool.
phpMyAdmin | Features: Let us now look into some of the features of phpMyAdmin tool.
• Manages all user level permissions.
• Executes SQL queries, batch queries, triggers, events, stored procedures, functions to
display relevant data results.
• It performs all data related operations like create, read, edit, delete, browse, change
structure, schema and search.
• It also provide ways to import, export and load text file data.
• It export data in various formats like CSV, XML, PDF, Word document, Latex,
Spreadsheet, Excel file and many more.
• It supports complex queries and bookmarking of SQL queries.
• It can also optimize, repair, change tables and views.
• It also supports InnoDB, foreign keys and MySQLi.
• It provides user friendly graphical interface to access website related data.
• It can provide PDF graphics layout of database.
• It is very flexible with different operating system.
• It can handle complex queries using Query by example.
• It provides multiple-server administration.
• It can control several servers at the same time.
phpMyAdmin | Advantages: Let us now look into some of the advantages of phpMyAdmin tool
in brief.
• Its very simple to set up the tool.
• The GUI is very convenient and easy to understand for developers and users.
• As its a web-based tool, it can be accessed it from any computer system.
• Its a intuitive web based interface which runs on any server.
• It is advantageous over console as many tasks like cut, copy and run queries becomes
very easy due to its GUI.
• It provides automatic MySQL backup facility.
• It don’t require a network connectivity as its installed on the computer already having
MySQL server.
• It provides maximum level of data security and efficiency for its client.
• It is supported by multi-language community.
phpMyAdmin | Configuration:
• Download the latest version of phpMyAdmin.
• Once the files are extracted during the download process, they are stored in
location C:\xampp\phpMyAdmin
• The configuration settings can be changed in config.inc.php file which is present in
the above location. Other system settings can also be changed in the file.
• Administrators have full rights for creating new users, remove users and modify
privileges for old users.
• For a specific database, you can define the permissions of any user and manage
accounts of user groups.
Note: The configuration settings are used to customize the web interface.
phpMyAdmin | Logging in: Whenever a user logs in to phpMyAdmin server with the username
and password, these values are passed directly to MySQL server. For logging in, you need the
valid credentials of MySQL users.
• Database server
• Database username
• Database password
Once all the credentials are entered correctly, you can see the phpMyAdmin home page in your
browser. When you are in phpMyAdmin page, the center section is the default General
Settings and Appearance Settings and in the right side, you can see Database server and Web
server information.
You can adjust language, themes, font size under the Appearance Settings section. You can also
change Database server information as needed.
All the list of databases can be seen on the left-hand side of the screen. You can select the database,
you want to work with out of the list. Once it is expanded, all the tables in the selected database
can be viewed.
phpMyAdmin tool allows you to check the MySQL server status by accessing the Status tab. For
checking status, remember NOT to select any specific database.
Here, you can find information regarding all the traffic your server has Received and Sent while
the MySQL server been running. It also shows the maximum concurrent connections,
and Failed attempts. If you are using a shared hosting plan, chances are your numbers won’t make
much sense. All these information helps in determining the amount of bandwidth consumed as you
are not the only one to use the server.
phpMyAdmin | Access of Database information: You can see information_schema database
in the left side of the screen. It is the database which stores all the information of all other databases
like name of databaseS, name of tables, column data type, access privileges and so on. It is a built-
in database created with the purpose of giving information about the whole database system.
In information_schema tables are automatically populated by the MySQL DB server.
phpMyAdmin | Create database: A user can create a database in phpMyAdmin server. Just click
on the Databases tab, you have a Create database input option. Give a relevant name for the
database in the entry box and click the Create button. The phpMyAdmin will create tables which
will be added under the newly created database.
You can add as many numbers of tables as required in one particular selected database by using
the section Create table and then the select number of columns needed for any table.
The phpMyAdmin will give an option to upload an SQL file to your server. Click on
the Import tab of the top screen and it will allow you to choose a file from any location. This helps
in creating database or tables as written in the imported file.
Note: In the same way, you can also export any table or database as a file by using Export tab.
phpMyAdmin | Execute a SQL query: Let us look into the steps to execute a SQL query on a
selected database.
• In the left side of the screen, select the database to work with. The Structure of the
database can be seen after the selection.
• Click SQL tab from top bar to open editor in which you can write the queries.
• Write the query into the SQL editor.
• You can also write multiple queries, with semicolon (;) separating different queries.
• Click Go button to execute the query. If the query is executed successfully, you will
get a success message.
Another way to run a SQL query in the database is by using Query tab. Using this you can give
many search conditions, query more than one table and also sort the results. You can even easily
pick all the columns needed for MySQL query by using Column drop down menus
and Show checkbox.
For sorting the result set in a query in an ascending or descending order, you can use
the Sort dropdown. You can also enter the criteria for the search query. The Ins and Del check
boxes or Add/Delete criteria rows options are provided to add or delete text rows for any search
conditions. The logical operators And or the Or can also be used to define relations between the
fields in the Modify section. After entering all the relevant conditions, you need to click
on Update Query button for doing the SQL operation. Next step is to select all the tables from Use
Tables section used in the query and then click on Submit Query.
phpMyAdmin | Operations: In the phpMyAdmin tool, different operations can be performed on
the database or on a separate table. Select the database for which you want to perform any operation
and click the Operations tab. It is allowed to create a new table under the selected database by
using Create table section. You can also rename the selected database by using Rename
database to section. Similarly you also have Remove database to delete database and Copy
database to sections which can be used as required for any SQL operation.
phpMyAdmin | Generate a search query: We can also generate a search query using
phpMyAdmin GUI, rather than writing the search query manually for a selected table. This can be
done by clicking the Search tab in the top menu of the screen.
phpMyAdmin | Insert query: We can also insert query using phpMyAdmin GUI, rather than
manually writing it. Select the table for which insert query will be executed. Then click
the Insert tab in the top menu of the screen. Once the relevant values are entered, the new record
will be inserted in the table. The newly inserted record can be viewed using the Browse tab under
the selected table name.
What is a session
Sessions are states that are saved to the server (like a unique ID), or if a user is logged into their
account.
NOTE Because sessions are not stored in the browser like cookies, it is a more secure option.
The application tracks these states and stores them as a session on the server. As soon as the user
is logged out, the session is destroyed.
To start a session in PHP, we use the session_start() function. We store session data by using
the $_SESSION superglobal.
Syntax:
// start a session
session_start();
// start a session
session_start();
?>
<html>
<body>
</body>
</html>
In the example above we also create an html hyperlink to another page, which will demonstrate
how sessions save data across pages.
If you have been following along with the course and you’re working in Atom, follow the steps
below.
We access session data in the same way we would access an array element.
?>
When we run the main.php file, it stores the session data. Clicking the link takes us to a new page
where we display the stored data. The username value survived across pages.
NOTE We must remember to start a session with the session_start() function, even on pages that
only access session data. The session start function will fetch an ongoing session if one has already
been started elsewhere.
Session variables are mutable, which means they can be changed during runtime. To change the
value of a session variable, we simply assign a new value to it.
Syntax:
$_SESSION["session_variable_name"] = "new_value";
Example: main.php - change session data
<?php
// start a session
session_start();
?>
<html>
<body>
</body>
</html>
In the example above, we change the username session variable from John to Jane. If we
run main.php and click on the link, the new name will be printed to the page.
If we want to clear out all the stored values from session variables, we use
the session_unset() function.
?>
After we unset the value of the username variable, we can no longer print it and the interpreter will
raise an Undefined index error.
Output:
Notice: Undefined index: username on line 10
?>
When the session is destroyed, both echo statements will not be able to print the username variable,
and the interpreter will raise an error.
Output:
Notice: Undefined index: username on line 4
Hello
Notice: Undefined index: username on line 10
NOTE It’s important to note that destroying a session may take some time, it is not always
immediate.
Typically, a session is destroyed after logout or checkout etc. to clean the session variable of the
user specific data.
What is a cookie
Cookies are states that are saved to the user’s system, instead of the server. Unlike a session, a
cookie has a 1024 byte size limit. Cookies are sent to the web server as header information in every
HTTP request.
NOTE Cookies are not stored on the server, they can be modified and deleted. Cookies are less
reliable and secure than sessions.
As an example, let’s consider an application with a member area. Once a user enters their log in
details, a cookie is created on that user’s system that saves those details.
If the user comes back to the application, the login details can be automatically filled into the form
so that the user doesn’t have to repeat the process.
Cookies are also commonly used to serve advertisements based on products that the user views
around the web. For example, if a user views a product on Amazon, they will find advertisements
of similar products when using Facebook or Google services.
The first argument, name, is mandatory for every cookie. The rest of the arguments are optional,
but recommended.
ArgumentUsage
name Required. The name the cookie will be referred to. Must be a string.
value Optional. The value of the cookie.
expiration Optional. If an expiration time is not set, the cookie will expire when the browser is closed.
path Optional. The path on the server the cookie will be available on. The cookie can be set to
'/' to be available to the entire domain.
domain Optional. The (sub)domain that the cookie is available to. Sub-domains of the specified
domain are automatically included.
secure Optional. If set to true, the cookie will only be set for a HTTPS secure connection.
Example: how to set a cookie
<?php
?>
The value portion of the cookie will automatically be urlencoded when the cookie is sent.
Characters such as a space and . will be converted to underscores. When the cookie is received, it
will be automatically decoded and assigned to a variable with the same name.
The expiration time is often confusing for many beginners that aren’t used to working with the
UNIX timestamp. In such a case we can use the strtotime() function which converts time from a
string into the correct time.
Syntax:
strtotime('+30 days')
Example: alternate expiration time
<?php
// Expires in 30 days
setcookie("UserID", 007, strtotime('+30 days'));
?>
How to access cookie data
We access a cookie’s value via the $_COOKIE superglobal by specifying its name as the key.
Syntax:
$_COOKIE["cookie_name"];
Example: access a cookie
<?php
?>
How to change cookie data
We can change any argument of the cookie, except the name, by assigning a new value. When a
new name is assigned, it will create a new cookie instead of changing the current cookie.
?>
How to delete a cookie
?>
When a cookie is deleted and we try to access it, the interpreter will raise an Undefined index error.
There is a risk of the user modifying their system’s time backwards so that the cookie does not
expire. We recommend that the cookie be set to expire one second into the future, instead of in the
past.
?>
How to test if cookies can be set
With all the privacy concerns these days, many users disable cookies in their browsers. If we want
to know if a cookie can be set in a user’s browser, we have to try and create a cookie. If the attempt
is successful, we know that cookies can be set.
setcookie("isAllowed", 1);
if(isset($_COOKIE["isAllowed"])) {
echo "Cookies are allowed";
} else {
echo "Cookies are not allowed";
}
?>
Summary: Points to remember
<?php
?>
Note:
• To retrieve cookies data in PHP use $_COOKIES.
• To check if it is set or not, use isset() function.
• PHP
<?php
Setcookie("username", "abc", time() + 60 * 60);
?>
<html>
<body>
<?php
if(isset($_COOKIE["username"])) {
echo "Cookie is set";
}
else {
echo "Cookie is not set";
}
?>
</body>
</html>
For updating cookies only, we need to change the argument by calling setcookie() function. We
change name “abc” to “xyz”.
• PHP
<?php
?>
• PHP
<?php
?>
Note: Drawback of using cookies is it can easily retrieve and also easily deleted. It is not secure.
Session:
• Session stores server-side information, so that all the information are accessible to all
the webpages.
• It is more secure than cookies.
• We know that HTTP is a stateless protocol so that previously performed task cannot be
remembered by current request.
For example, when we want to buy something online, we visit many e-commerce websites and
compare products. Some of them are added to cart for future reference. After few days when we
are ready to buy it, the information is still available as the cart session is set earlier.
Session is size independent to store as many data the user wants.
Uses of Session:
1. It provides login and logout functionality to store and display relevant information.
2. It maintains cart of e-commerce.
Creation of Session: In PHP, session starts from session_start() function and data can be set and
get by using global variables $_SESSION.
Example:
• PHP
<?php
session_start();
$SESSION["username"] = "abc";
$SESSION["userid"] = "1";
?>
<html>
<body>
<?php
echo "Session variable is set";
?>
<button type="submit" href="logout.html"></button>
</body>
</html>
• PHP
<?php
?>
Output:
Username abc
Userid 1
For updating the value of session variable
$_SESSION["userid"]="1024";
To destroy session in PHP, first unset all the session variable using session_unset() and
call session_destroy() methods.
• PHP
<?php
session_start();
?>
<html>
<body>
<?php
session_unset();
session_destroy();
?>
</body>
</html>
PHP Cookies
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
Create Cookies With PHP
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
The following example creates a cookie named "user" with the value "John Doe". The cookie will
expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire website
(otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also
use the isset() function to find out if the cookie is set:
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).
To modify a cookie, just set (again) the cookie using the setcookie() function:
Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
The following example creates a small script that checks whether cookies are enabled. First, try
to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
For a complete reference of Network functions, go to our complete PHP Network Reference.
PHP Exercises
Exercise:
<?php
$data = serialize(array("Red", "Green", "Blue"));
echo $data;
?>
Definition and Usage
To serialize data means to convert a value to a sequence of bits, so that it can be stored in a file, a
memory buffer, or transmitted across a network.
Syntax
serialize(value);
Parameter Values
Parameter Description
Technical Details
Return Value: A string that contains a byte-stream representation of value. The string can be
stored anywhere