Chapter 5
Chapter 5
PHP communicates with relational databases such as MySQL and Oracle using the Structured Query
Language (SQL). Programmers can use SQL to create, modify, and query relational databases.
The syntax for SQL is divided into two parts. The first, Data Manipulation Language or DML, is used to
retrieve and modify data in an existing database. DML is remarkably compact, consisting of only four
actions or verbs: SELECT, INSERT, UPDATE, and DELETE.
The set of SQL commands used to create and modify the database structures that hold the data is known as
Data Definition Language, or DDL. The syntax for DDL is not as standardized as that for DML, but as PHP
just sends any SQL commands programmer give to the database, can use any SQL commands that database
supports.
Creating a database in MySQL - Through Xampp server
XAMPP stack of software is an open-source localhost server providing a number of functionalities through
the package of software it contains. The software, which is part of XAMPP is started/stopped using
the XAMPP Control Panel. It is used for testing the projects and modifications offline before launching it on
the global web. One such very important functionality provided by XAMPP is the creation of the MySQL
database. This is done by using phpMyAdmin.
phpMyAdmin : phpMyAdmin is a costless and open source software that provides the functionality of
operating and managing MySQL over the internet. It provides an ease to the user to control and supervise
the database with the help of a graphic user interface known as phpMyAdmin.This GUI is written in PHP
programming language. The user can operate upon MySQL via phpMyAdmin user interface while still
directly executing SQL queries. The GUI allows the host to carry a number of manipulation operations on
the database, such as editing, creating, dropping, amending, alteration of fields, tables, indexes, etc. It can
also be used to manage access control over the data by giving privileges and permissions.
Step 1 : Click on Start and select XAMPP from the list. Open Xampp control panel by clicking on the option
from the list. The Control Panel is now visible and can be used to initiate or halt the working of any module.
Step 2 : Click on the "Start" button corresponding to Apache and MySQL modules. Once it starts working,
the user can see the following screen:
Step 3 : Now click on the "Admin" button corresponding to the MySQL module. This automatically
redirects the user to a web browser to the following address - http://localhost/phpmyadmin
Step 4 : Screen with multiple tabs such as Database, SQL, User Accounts, Export, Import, Settings, etc. Will
appear. Click on the "Database" tab. Give an appropriate name for the Database in the first textbox and click
on create option.
Step 5 : In the created Database, click on the 'Structure' tab. Towards the end of the tables list, the user will
see a 'Create Table' option. Give appropriate "Name" and "Number of Columns" for table and click on
'Go' button.
Step 6 : Give details of columns based on their type. Enter the names for each column, select the type, and
the maximum length allowed for the input field. Click on "Save" in the bottom right corner. The table with
the initialized columns will be created.
OR
One can create database and table with code as shown below using MySQLi Object
Interface :
Creating database :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password); // creating object of mysqli class
if ($conn->connect_error) // checking error in database connectivity
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "CREATE DATABASE ifdept";
if ($conn->query($sql) === TRUE)
{
echo "Database created successfully";
}
else
{
echo "Error creating database: " . $conn->error; // displays error if error in execution of query
}
$conn->close();
?>
$conn->connect_error : It is used to check error in database connectivity. It return error information if
error occurs in connectivity. For example, if the specified database is not available on given path then it
returns the result as ‘unknown database along with its name’. If connection is successful (without any error)
then connect_error returns NULL value.
If queries are executing successfully then $conn->query($sql) returns TRUE value otherwise returns false
value.
Creating Table :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ifdept";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "CREATE TABLE student (
rollno INT(4),
name VARCHAR(30)
)";
if ($conn->query($sql) === TRUE) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
?>
$conn->close();
5.3 Data base operations : Insert data, retrieving the query result
Insert data :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ifdept";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO student (rollno, name)VALUES (2,'shrisha')";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
} else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
***************************************************************************************
One can create database and table with code as shown below using MySQLi Procedural
interface :
Creating database :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Creating Table :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";
if (mysqli_query($conn, $sql))
{
echo "Table MyGuests created successfully";
} else
{
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Connecting to a MySQL database : MySQL database server from PHP :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = mysqli_connect($servername, $username, $password);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Data base operations : Insert data, retrieving the query result
Insert data :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Retrieving the query result :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Update and delete operations on table data
Update data :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Delete data :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
************************************************************************************
One can create database and table with code as shown below using PDO - PHP Data Object :
Creating database :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try
{
$conn = new PDO("mysql:host=$servername", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE myDBPDO";
$conn->exec($sql);
echo "Database created successfully<br>";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
Creating Table :
<?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;
?>
Connecting to a MySQL database : MySQL database server from PHP :
<?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();
}
?>
Data base operations : Insert data, retrieving the query result
Insert data :
<?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', '[email protected]')";
// 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;
?>
Retrieving the query result :
<?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();
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;
?>
Delete data :
<?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;
?>