0% found this document useful (0 votes)
28 views

Chapter 5

Uploaded by

34Shreya Chauhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Chapter 5

Uploaded by

34Shreya Chauhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Chapter 5

5.1 Introduction to MYSQL -Create a database


There are two ways to access databases from PHP.
1. Use a database-specific extension
2. Use the database-independent PDO (PHP Data Objects) library.

There are advantages and disadvantages to each approach :


Portability :
With the,database-specific extension, code is intimately tied to the database in use. For example, the
MySQL extension’s function names, parameters, error handling, and so on are completely different from
those of the other database extensions. If programmer want to move the database from MySQL to
PostgreSQL, it will involve significant changes to the code i.e. portability need changes in the code.
PDO hides the database-specific functions from programmer with an abstraction layer, so moving between
database systems can be as simple as changing one line of the program or the php.ini file.
Speed :
The portability of an abstraction layer like the PDO library comes at a price, however, as code that uses it is
also typically a little slower than code that uses a native database specific extension.

Relational Databases and SQL


A Relational Database Management System (RDBMS) is a server that manages data for programmer. The
data is structured into tables, where each table has a number of columns, each of which has a name and a
type. For example, to keep track of science fiction books, we might have a “books” table that records the
title (a string), year of release (a number), and the author.
Tables are grouped together into databases, so a science fiction book database might have tables for time
periods, authors, and villains. An RDBMS usually has its own user system, which controls access rights for
databases (e.g., “user Fred can update database authors”).

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();
?>

5.2 Connecting to a MySQL database : MySQL database server from PHP


Code :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Close the Connection :
The connection will be closed automatically when the script ends. Close() function returns True value if
connection with database is closed successfully or else returns false. To close the connection before, use the
following:

$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();
?>

Retrieving the query result :


<?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 = "SELECT rollno, name FROM student";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc()) // fetch_assoc()- Used to read data from associative array.
{
echo "rollno: " . $row["rollno"]. " - Name: " . $row["name"]."<br>";
}
} else
{
echo "0 results";
}
$conn->close();
?>
Output :
rollno: 1 - Name: Swara
rollno: 1 - Name: shrisha
rollno: 2 - Name: shrisha

5.4 Update and delete operations on table data


Update 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 = "UPDATE student SET rollno=4 WHERE name='shrisha'";
if ($conn->query($sql) === TRUE)
{
echo "Record updated successfully";
} else
{
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
Delete 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 = "DELETE FROM student WHERE rollno=2";

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


echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $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);

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";
$conn->exec($sql);
echo "Table MyGuests created successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}

$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>";

class TableRows extends RecursiveIteratorIterator {


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

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

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

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

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

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

// set the resulting array to associative


$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
Update and delete operations on table data
Update 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 = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

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

// execute the query


$stmt->execute();

// echo a message to say the UPDATE succeeded


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

$conn = null;
?>

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);

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";
// use exec() because no results are returned
$conn->exec($sql);
echo "Record deleted successfully";
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

You might also like