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

Unit-V Database Operations

The document provides an overview of MySQL, covering its introduction, features, data types, and basic database operations such as creating, connecting, inserting, updating, and deleting data. It explains MySQL's client/server architecture, compatibility with various operating systems, and its use in web applications. Additionally, it outlines common MySQL commands and the process for accessing MySQL via command line and web interfaces.

Uploaded by

catstudysss
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit-V Database Operations

The document provides an overview of MySQL, covering its introduction, features, data types, and basic database operations such as creating, connecting, inserting, updating, and deleting data. It explains MySQL's client/server architecture, compatibility with various operating systems, and its use in web applications. Additionally, it outlines common MySQL commands and the process for accessing MySQL via command line and web interfaces.

Uploaded by

catstudysss
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Database Operations

5
UNIT V

Syllabus

5.1 Introduction to MySQL, Create a Database.

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

5.3 Database Operations: Insert data, Retrieving the Query Result.

5.4 Update and Delete operations on table data

− SELECT name FROM student WHERE rollno=33;


5.1 Introduction to MySQL
− A MySQL database contains one or more tables, each
− MySQL is used to manage stored data and is an open of which contains records orrows. Within these rows
source Database Management Software (DBMS) or are various columns or fields that contain the data
Relational Database Management System (RDBMS). itself.

− Its name My-S-Q-L is often pronounced as My Sequel − Each row in the table is the same as a row in a MySQL
is a combination of “My”, the name of co- table, and each element within a row is the same as a
founders Michael Widenius's daughter, and "SQL", the MySQL field.
abbreviation for Structured Query Language. − PHP and MySQL are server side technologies, both are
− MySQL was owned and sponsored by used on server side so the combination of these is
the Swedish company MySQL AB, which was acquired preferred to developed cloud based application.
by Sun Microsystems. − MySQL operates using client/server architecture in
− MySQL is one of the best RDBMS being used for which the server runs on the machine containing the
developing various web-based software applications. databases and clients connect to the server over a
network. The server (MySQL server) listens for client
− MySQL is a main component of web
requests coming in over the network and accesses
application software’s like XAMPP, LAMP and WAMP.
database contents according to those requests and
− MySQL is used by many database-driven web provides that to the clients.
applications which includes Drupal, Joomla, phpBB,
− Clients are programs that connect to the database
and WordPress.
server and issue queries in a pre-specified format.
− MySQL is also used by many popular websites which MySQL is compatible with the standards based SQL
includes Facebook, Flickr, MediaWiki, Twitter (SQL stands for Structured Query Language) language.
and YouTube. The client program may contact the server
programmatically (meaning a program call the server
− It is designed to allow simple requests from a
during execution) or manually.
database via commands such as
Web Based Application Development using PHP (MSBTE) 5-2 Database Operations

− Typically, mySQL is supported on Windows XP, − High Performance: MySQL is faster, more reliable and
Windows Server 2003, Red Hat Fedora Linux, and cheaper because of its unique storage engine
Debian Linux, and others. As with any other architecture.
client/server application, MySQL is a multi-user
− No License Fee:MySQL is available free of
database system, meaning several users can access
cost. MySQL is a "Open Source" database. MySQL is
the database simultaneously.
part of LAMP (Linux, Apache, MySQL, PHP / Perl /
5.1.1 Features of MySQL Python) environemtn, a fast growing open source
enterprise software stack. This reduces licensing costs
Q. Explain features of MySQL. and hardware expenditures.

− Easy to use: MySQL is easy to use. With the basic − Security: MySQL supports powerful mechanisms to
knowledge of SQL, you can build and interact with ensure that only authorized users have access to the
MySQL.MySQL has typically been configured, databases. MySQL consist of a solid data security layer
monitored, and managed from the command line. that protects sensitive data from intruders. Passwords
However, several MySQL are available with graphical are encrypted in MySQL.
interfaces. − High Availability: MySQL can run high-speed
− Free to download: MySQL is free to use and you can master/slave replication configurations and it offers
download it from MySQL official website. cluster servers.

− Ease of Management: The software very easily gets − Scalability: MySQL can handle almost any amount of
downloaded and also uses an event scheduler to data, up to as much as 50 million rows or more. The
schedule the tasks automatically. default file size limit is about 4 GB. However, you can
increase this number to a theoretical limit of 8 TB of
− Client/ Server Architecture: MySQL follows a client data.
/server architecture. There is a database server
(MySQL) and arbitrarily many clients (application − High Flexibility: MySQL supports a large number of
programs), which communicate with the server; that embedded applications which makes MySQL very
is, they query data, save changes, etc. flexible.

− Compatible on many operating systems: MySQL is − High Productivity: MySQL uses Triggers, Stored
compatible to run on many operating systems, like procedures and views which allows the developer to
Novell NetWare, Windows OS, Linux OS, many give a higher productivity.
varieties of UNIX, OS/2, FreeBSD*, and others. MySQL − Speed: The speed at which a server side program runs
also provides a facility that the clients can run on the depends on the server hardware. MySQL runs very
same computer as the server or on another computer fast even server hardware is optimal. It supports
(communication via a local network or the Internet). clustered servers for demanding applications
− Robust Transactional Support: Holds the ACID
5.1.2 MySQL Tools
(Atomicity, Consistency, Isolation, Durability)
property, and also allows distributed multi-version − A SQL server: This is an engine which provides access
support. to your databases.
− Comprehensive Application Development : MySQL − Client programs for accessing the server: A program
has plugin libraries to embed the database into any allows you to enter queries directly and view results.
application. It also supports stored procedures,
− A client library for writing your own programs: You
triggers, functions, views and many more for
can write your own programs into the client library
application development.
using C.
Web Based Application Development using PHP (MSBTE) 5-3 Database Operations

5.1.3 Data Types in MySQL Data Type Size Description

− A Data Type specifies a particular type of data, like TEXT(size) Maximum 65,535 Where size is
integer, floating points, Boolean etc. characters. the number of
characters to
− MySQL supports a number of SQL standard data types
store.
in various categories.
MEDIUMTEXT(size Maximum Where size is
− It uses many different data types broken into mainly
16,777,215 the number of
three categories: numeric, date and time and string
characters/Binary characters to
types.
Large Object. store.
1. String Data Types : String Data types allow both fixed
and variable length strings. LONGTEXT(size Maximum 4GB or Where size is
4,294,967,295 the number of
Data Type Size Description characters/Binary characters to
CHAR(size) Maximum 255 Fixed-length Large Object store.
characters. Character BINARY(size) Maximum 255 A fixed-length
strings. characters. binary string
VARCHAR(size) Maximum 255 Variable- VARBINARY(size) Maximum 255 A variable-
characters. length string. characters. length binary
TINYTEXT(size) Maximum 255 Where size is string
characters. the number of
characters to
store.

2. Numeric Data Types : Numeric Datatypes allow both signed and unsigned integers.

Data Type Size Description

Signed values range from -128 to 127. Unsigned values


BIT A bit field
range from 0 to 255.

Signed values range from -128 to 127. Unsigned values


TINYINT(m) range from 0 to 255. Very small integer value.
(1 byte)

Signed values range from -32768 to 32767. Unsigned


SMALLINT(m) Small integer value.
values range from 0 to 65535. (2 byte)

Signed values range from -8388608 to 8388607. Unsigned


MEDIUMINT(m) Medium integer value.
values range from 0 to 16777215. (3 byte)

INT(m)/ Signed values range from -2147483648 to 2147483647.


Standard integer value.
INTEGER(m) Unsigned values range from 0 to 4294967295. (4 bytes)

Signed values range from -9223372036854775808 to


BIGINT(m) Big integer value.
9223372036854775807. Unsigned values range from 0 to
Web Based Application Development using PHP (MSBTE) 5-4 Database Operations

Data Type Size Description

18446744073709551615. (8 bytes)

DECIMAL(m,d)/

DEC(m.d)/ m defaults to 10, if not specified. d defaults to 0, if not


Unpacked fixed point number.
NUMERIC(m,d)/ specified.

FIXED(m,d)

Where m is the total digits and d is the number of digits


FLOAT(m,d) after the decimal. Single precision floating point number.
(4 bytes)

Where m is the total digits and d is the number of digits


DOUBLE(m,d)/
after the decimal. Double precision floating point number.
REAL(m,d)
(8 bytes)

FLOAT(p) Where p is the precision Floating point number.

BOOL/ Treated as a Boolean data type where a


Synonym for TINYINT(1) value of 0 is considered to be FALSE and
BOOLEAN any other value is considered to be TRUE.

3. Date and Time Data Types : MySQL provides types for date and time as well as the combination of date and time.

Data Type Size Description

Values range from '1000-01-01' to '9999-12-


DATE() Displayed as 'yyyy-mm-dd'.
31'. (3 bytes)

Values range from '1000-01-01 00:00:00' to


DATETIME() '9999-12-31 23:59:59'. Displayed as 'yyyy-mm-ddhh:mm:ss'.
(8 bytes)

Values range from '1970-01-01 00:00:01' UTC Displayed as 'YYYY-MM-DD


TIMESTAMP(m)
to '2038-01-19 03:14:07' TC. (4 bytes) HH:MM:SS'.

Values range from '-838:59:59' to '838:59:59'.


TIME() Displayed as 'HH:MM:SS'.
(3 bytes)

Year value as 2 digits or 4 digits.


YEAR[(2|4)] Default is 4 digits.
(1 byte)

Large Object Data Types (LOB) Data Types :


Data types Size
TINYBLOB Maximum size of 255 bytes.
BLOB(size) Maximum size of 65,535 bytes.
MEDIUMBLOB Maximum size of 16,777,215 bytes.
LONGTEXT Maximum size of 4gb or 4,294,967,295 characters.
Web Based Application Development using PHP (MSBTE) 5-5 Database Operations

5.1.4 Accessing MySQL via the Command Line

There are three main ways in which you can interact with MySQL:

1. Command line

2. Web interface such as phpMyAdmin,

3. Programming language like PHP

Starting the Command-Line Interface

1. Windows users

− After installing XAMPP, you will be able to access the MySQL executable from the following directory :
C:\xampp\mysql\bin

− If anyone wants to install XAMPP in a place other than \xampp, you will need to use that directory instead.

− MySQL default user will be root and will not have had a password set.

− In order to enter MySQL’s command-line interface, select Start→Run, enter CMD into the Run box, and press Return.

− This will call up a Windows command prompt. From there, enter one the following (making any appropriate changes
as just discussed):

C:\xampp\mysql\bin\mysql -u root

− Using this command you are asking MySQL to log you in as user root, without a password.
− After logging, MySQL you can start entering commands, for checking whether everything is working as it should be,
enter the following command;

− SHOW databases;

2. Linux users

− On a system running a Unix-like operating system such as Linux, you will almost certainly already have PHP and
MySQL installed and running
Web Based Application Development using PHP (MSBTE) 5-6 Database Operations

− First you should type the following to log into your Command Action
MySQL system:
LOCK Lock table(s)
mysql -u root -p
QUIT (\q) Same as EXIT
− This tells MySQL to log you in as the user root and to
RENAME Rename a table
request your password. If youhave a password, enter
it; otherwise, just press Return. SHOW List details about an object
− Once you are logged in, type the following to test the SOURCE Execute a file
program; you should see something like Figure in
STATUS (\s) Display the current status
response:
TRUNCATE Empty a table
SHOW databases;
UNLOCK Unlock table(s)
(C/O – Figure not given Plz check)
UPDATE Update an existing record
5.1.5 MySQL Commands
USE Use a database
− SQL commands and keywords are case-insensitive.
− It is recommended to use uppercase for all database
5.1.6 Database Related Commands
operations.

− Table names are case-sensitive on Linux, but case- 5.1.6(A) Creating a Database
insensitive on Windows. So for portability purposes,
you should always choose a case and stick to it. It is − A database is a collection of data. MySQL allows us to
recommended to use lowercase for tables. store and retrieve the data from the database in a
efficient way.
− The commonly used MySQL commands are listed in
Table. − We can create a database using the CREATE
DATABASE statement. But, if database already
Table 5.1.1 : Common MySQL commands
exits, it throws an error. To avoid the error, we can
Command Action use the IF NOT EXISTS option with the CREATE
DATABASE statement.
ALTER Alter a database or table
Syntax : CREATE DATABASE <database name>;
BACKUP Back up a table
− If a successful command execution will return a
\c Cancel input message that doesn’t mean much yet—Query OK,
CREATE Create a database 1 row affected (0.00 sec)—but will make sense soon.

DELETE Delete a row from a table − We can use created database for use using MySQL
USE command
DESCRIBE Describe a table’s columns
USE <database name>;
DROP Delete a database or table
− You should now see the message Database changed
EXIT (CTRL-C) Exit and will be able to see the database name in the
GRANT Change user privileges prompt.

HELP (\h, \?) Display help − For example, we will create database with the name
college using CREATE command and we will use it by
INSERT Insert data using USE command
Web Based Application Development using PHP (MSBTE) 5-7 Database Operations

Example : − We should be careful while deleting any database


because we will loose all the data available in the
MariaDB [(none)]> CREATE DATABASE college;
database.
Query OK, 1 row affected (0.01 sec)
Syntax : DROP DATABASE database_name;

MariaDB [(none)]> USE college; 5.1.7 Table Related Commands

Database changed 5.1.7(A) Creating a Table


MariaDB [college]>
− In order to create a table we have to choose an
appropriate database for operation using USE
You can check the created database by the following query: command

MariaDB [(none)]> show databases; − Table can be created using CREATE TABLE command
into the database and by mentioning the fields with
+---------------------------+
its type.
| Database |
Syntax : CREATE TABLE [IF NOT EXISTS] <table name>
+---------------------------+ (<field name>dataType [optional parameters])
| college | ENGINE = storage Engine;
| information_schema | − Example a student table is created in a college
| mysql | database, a table is created with columns rollno,
name and percentage
| performance_schema|
Example :
| phpmyadmin |
| test | MariaDB [(none)]> USE college;
+--------------------------+ Database changed
6 rows in set (0.002 sec)
MariaDB [college]> CREATE TABLE student(
5.1.6(B) Select Databases
->rollnoVARCHAR(16),
− SELECT Database is used in MySQL to select a -> name VARCHAR(128),
particular database to work with, when multiple
databases are available with MySQL Server.
-> percent float(5,2))ENGINE MyISAM;
Query OK, 0 rows affected (0.19 sec)
Syntax : USE database_name;
− After execution of the command it generates a
MariaDB [(none)]> use college
response Query OK, 0 rows affected, along with how
Database changed long it took to execute the command. If you see an
MariaDB [college]> error message instead, check your syntax carefully.

− Every parenthesis and comma counts, and typing


5.1.6(C) Drop Database
errors are easy to make.
− We can drop/delete/remove a MySQL database easily − The ENGINE MyISAM tells MySQL the type of
with the MySQL DROP DATABASE command. database engine to use for this table
− It deletes all the tables of the database along with the
database permanently.
Web Based Application Development using PHP (MSBTE) 5-8 Database Operations

5.1.7(B) Describe Command 5.1.7(C) Adding Data to a Table

− For checking whether your new table has been − INSERT command can be used to add data in a table.
created we can use DESCRIBE command:
Syntax : INSERT INTO <table name>
Syntax : DESCRIBE<table name>; (column_1,column_2,...) VALUES (value_1,value_2,...);

− For example student can be checked using DESCRIBE − For Example, three rows are inserted in the table
command. student using IINSERT command

MariaDB [college]> DESCRIBE student; MariaDB [college]> INSERT INTO


student(rollno,name,percent) VALUES
+-----------+------------------+-------+-----+-----------+---
('CO101','Prasad Koyande',95.45);
------+
Query OK, 1 row affected (0.07 sec)
| Field | Type | Null | Key | Default | Extra |
MariaDB [college]> INSERT INTO
+-----------+------------------+-------+-----+-----------+---
student(rollno,name,percent) VALUES
------+
('CO102','Vijay Patil',96.85);
| rollno| varchar(16) | YES | | NULL ||
Query OK, 1 row affected (0.00 sec)
| name | varchar(128) | YES | | NULL | |
MariaDB [college]> INSERT INTO
| percent | float(5,2) | YES | | NULL | | student(rollno,name,percent) VALUES
+-----------+-------------------+-------+----+-----------+--- ('CO103','Yogita Khandagale',98.45);
------+ Query OK, 1 row affected (0.00 sec)
3 rows in set (0.03 sec) − After every second line, you should see a Query OK
− The DESCRIBE command is an invaluable debugging message. Once all lines have been entered, type the
aid when you need to ensure that you have correctly following command, which will display the table’s
created a MySQL table. contents.

− You can also use it to remind your self about a table’s − The first part, INSERT INTO student, tells MySQL
field or column names and the types of data in each where to insert the following data. Then, within
one. Let’s look at each of the headings in detail: parentheses, the three column names are listed-
rollno, name and percent—all separate by commas.
1. Field : The name of each field or column within a This suggests that these are the fields into which the
table. data is to be inserted.
2. Type : The type of data being stored in the field. − The second line of each INSERT command contains
3. Null : Whether a field is allowed to contain a value of the keyword VALUES followed by four strings within
NULL. parentheses, and separated by commas. This supply
MySQL with the four values to be inserted into the
4. Key : MySQL supports keys or indexes, which are quick
three columns previously specified.
ways to look up and search for data. The Key heading
shows what type of key (if any) has been applied. − Each item of data will be inserted into the
corresponding column, in a one-to-one
5. Default : The default value that will be assigned to the
correspondence.
field if no value is specified when a new row is
created. − If listing of the column is done in the wrong order of
the data, the data would go into the wrong columns.
6. Extra : Additional information, such as whether a field
is set to auto-increment. − The number of columns must match the number of
data items
Web Based Application Development using PHP (MSBTE) 5-9 Database Operations

5.1.7(D) Deleting a Table − Syntax: SELECT something FROM <tablename>;

− Deleting a table is very easy. − The something can be an * (asterisk) as you saw
before, which means every column, or you can choose
− Table can be deleted using DROP TABLE command to select only certain columns.
Syntax : DROP TABLE <table name>; − For Example shows how to select just the rollno and
− For Example, we have created a table name ‘sample’ name from table student.
with a field ‘no’ which can be deleted using DROP Example.
TABLE command.
MariaDB [college]> SELECT rollno,name from
MariaDB [college]> CREATE TABLE sample(no student;
INT);
+--------+-------------------------+
Query OK, 0 rows affected (0.30 sec)
| rollno| name |
+--------+-------------------------+
MariaDB [college]> DESCRIBE sample;
| CO101 | Prasad Koyande |
+-------+-----------+------+------+---------+----------+
| CO102 | Vijay Patil |
| Field | Type | Null | Key | Default | Extra |
| CO103 |YogitaKhandagale |
+-------+-----------+-------+-----+---------+----------+
+--------+-------------------+
| no | int(11) | YES | | NULL | |
3 rows in set (0.00 sec)
+-------+-----------+-------+-----+---------+----------+
1 row in set (0.03 sec) 2. DELETE Command

− A row from a table can be removed using DELETE


command.
MariaDB [college]> DROP TABLE sample;
− The syntax is similar to the SELECT command and
Query OK, 0 rows affected (0.40 sec)
allows you to narrow down the exact row or rows to
delete using qualifiers such as WHERE and LIMIT.
MariaDB [college]> SHOW tables; − For example, a student with a roll no CO103 can be
+----------------------+ removed from the table using DELETE command and
| Tables_in_college | with where qualifiers.

+----------------------+ Example :

| student | MariaDB [college]> DELETE from student where


+---------------------+ rollno='CO103';

1 row in set (0.00 sec) Query OK, 1 row affected (0.03 sec)
MariaDB [college]> SELECT * from student;

MariaDB [college]> +--------+----------------+---------+


| rollno| name | percent |
5.1.8 Querying a MySQL Database
+--------+----------------+---------+
1. SELECT Command | CO101 | Prasad Koyande | 95.45 |
− The SELECT command is used to extract data from a | CO102 | Vijay Patil | 96.85 |
table. +--------+----------------+---------+
Web Based Application Development using PHP (MSBTE) 5-10 Database Operations

2 rows in set (0.05 sec) strings. LIKE qualifier should be used with a %
character before or after some text. When placed
3. WHERE Command before a keyword, % means anything before and after
a keyword, it means anything after.
− The WHERE keyword enables you to narrow down
queries by returning only those where a certain − The % will also match if there is nothing in the
expression is true. position it occupies; in other words, it can match an
empty string.
− For Example, we want to display the record with a roll
no CO101 can be fetched using WHERE and the − For Example, it searches all the name of the students,
equality operator =. which starts with Vijay, for doing so we have to use
LIKE qualifier and the % character after Vijay.
− Example : Using the WHERE keyword
Example :
MariaDB [college]> SELECT * FROM student
WHERE rollno="CO101"; MariaDB [college]> SELECT * FROM student
+-----------+----------------------+-----------+ WHERE name like "Vijay%";
| rollno| name | percent | +--------+-------------+---------+
+-----------+----------------------+---------- -+ | rollno | name | percent |
| CO101 | Prasad Koyande | 95.45 | +--------+-------------+---------+
+-----------+----------------------+------------+ | CO102 | Vijay Patil | 96.85 |
row in set (0.00 sec) +--------+-------------+---------+
1 row in set (0.00 sec)

− User can also do pattern matching, for searches using


the LIKE qualifier, which allows searches on parts of

5.1.9 Accessing MySQL via phpMyAdmin

− Web interface is much quicker and simpler to use a program such as phpMyAdmin to manage your databases and
tables.

− To use this, type the following to call up the XAMPP main page shown in Fig. 5.1.1.

http://localhost/xampp
Web Based Application Development using PHP (MSBTE) 5-11 Database Operations

Fig. 5.1.1 : XAMPP Main Page


− On the right top of the XAMPP main page you will be able to see phpMyAdmin menu, on that menu the main
pagephpMyAdmin screen will appear, you can click to select anydatabase you wish to work with. This will open the
database and display its tables.

Fig. 5.1.2 : phpMyAdmin Main Page

− You can also click New to create a new database. From here you can perform all the main operations, such as creating
new databases, adding tables, creating indexes, and much more. To read the supporting documentation for
phpMyAdmin, visit https://docs.phpmyadmin.net.

5.1.10 MySQL Storage Engine

Q. List storage engine in MySQL. Explain any one.

− A storage engine is a software module that a database management system uses to create, read, update data from a
database.

− There are two types of storage engines in MySQL: transactional and non-transactional.

− There are many storage engines available in MySQL and they are used for different purposes.

− The show engines command shows all available engines that the server supports.

Engine Description

MyISAM MyISAM is the original storage engine, fast storage engine manages non transactional
tables, provides high-speed storage and retrieval, supports full text searching. It is used
mostly in Web and data warehousing.

InnoDB his is the default storage engine for MySQL 5.5 and higher. It provides transaction-safe
(ACID compliant) tables, supports FOREIGN KEY referential-integrity constraints. It
supports commit, rollback, and crash-recovery capabilities to protect data. It also
supports row-level locking. Increases performance when used in a multiuser
environment. It stores data in clustered indexes which reduces I/O for queries based on
Web Based Application Development using PHP (MSBTE) 5-12 Database Operations

Engine Description
primary keys.

MEMORY Provides in-memory tables, formerly known as HEAP. It sores all data in RAM for faster
access than storing data on disks. Useful for quick looks up of reference and other
identical data. Memory storage engine is ideal for creating temporary tables or quick
lookups. The data is lost when the database is restarted.

MERGE Groups more than one similar MyISAM tables to be treated as a single table, can handle
non transactional tables, included by default. Merge tables help manage large volumes of
data more easily. Good for data warehousing environments.

EXAMPLE You can create tables with this engine, but cannot store or fetch data. Purpose of this is
to teach developers about how to write a new storage engine.

ARCHIVE Archive storage engine is optimized for high speed inserting. It compresses data as it is
inserted. It does not support transactions. It is ideal for storing and retrieving large
amounts of seldom referenced historical, archived data.

CSV CSV stores data in CSV (Comma Separated Value format in a text file)files. It provides
great flexibility because data in this format is easily integrated into other applications.

BLACKHOLE The Blackhole storage engine accepts but does not store data. Retrievals always return an
empty set. The functionality can be used in distributed database design where data is
automatically replicated, but not stored locally. This storage engine can be used to
perform performance tests or other testing.

FEDERATED Stores data in a remote database.Federated storage engine offers the ability to separate
MySQL servers to create one logical database from many physical servers. Queries on the
local server are automatically executed on the remote (federated) tables. No data is
stored on the local tables. It is good for distributed environments.

− PHP commands will retrieve the data and format it in


5.2 Connecting to MySQL Database the form that can be displayed on a web page.

− PHP used as an interface to a MySQL it will be used to 5.2.1 Connecting MySQL Database Server
format the results which are returned from from PHP
SQLqueries in a form that can be visible on a web
page. − The Process : The process of using MySQL with PHP is
as follows :
− Using PHP we can perform all operations that we can
perform using MySQL server using the correct 1. Connect to MySQL and select the database to
username and password. use.

− However, instead of using MySQL’s command line to 2. Build a query string.


enter instructions and view output,you will create 3. Perform the query.
query strings that are passed to MySQL.
4. Retrieve the results and output them to a web
− Query String gets executed and MySQL returns page.
itsresponse, it will come as a data structure that PHP
5. Repeat steps 2 to 4 until all desired data has
can recognize instead of the formattedoutput you see
been retrieved.
when you work on the command line.
Web Based Application Development using PHP (MSBTE) 5-13 Database Operations

6. Disconnect from MySQL. mysql.myserver.com, you can just use the word
localhost (or the IP address 127.0.0.1).
5.2.2 Creating a Login File
− We will be using, $db for specifying a database.
− When a web site is developed with PHP it contains
multiple program files that will require access to 5.2.3 Connecting to a MySQL Database
MySQL and will thus need the login and password
− All login credentials that are used to log MySQL server
details.
are saved in file login.php, you can include it in any
− Therefore, it is good to create a single file to store PHP files that will need to access the database by
login credentials and then include that file wherever it using the require_once statement.
is needed.
− This is prefer able to an include statement, as it will
Example . The login.php file generate a fatal error if the file is not found. And
believe me, not finding the file containing the login
<?php
details to your database is a fatal error.
$hn = 'localhost';
− Also, using require_once instead of require means
$db = 'college'; that the file will be read in only when it has not
$un = 'root'; previously been included, which prevents wasteful
$pw = ''; duplicate disk accesses.

?> Example Connecting to a MySQL server with


mysqli
− Type the example, replacing username and password
with the values you use for your MySQL database. <?php

− The hostname localhost should work as long as you


require_once 'login.php';
are using a MySQL database on your local system, and $conn = new mysqli($hn, $un, $pw, $db);
the database publications should work if you are if ($conn->connect_error) die($conn-
typing the examples. >connect_error);
− The enclosing <?php and ?> tags are especially ?>
important for the login.php file, because they mean
− This example creates a new object called $ conn by
that the lines between can be interpreted only as PHP
calling a new instance of the mysqli method, passing
code.
all the values retrieved from the login.php file. Error
− If you were to leave them out and someone were to checking is achieved by referencing the
call up the file directly from your website, it would $conn->connect_error property.
display as text and reveal your secrets. But, with the
− The -> operator indicates that the item on the right is
tags in place, all that person will see is a blank page.
a property or method of the object on the left. In this
The file will correctly include in your other PHP files.
case, if connect_error has a value, then there was an
− The $hn variable will tell PHP which computer to use error, so we call the die function and display that
when connecting to a database. This is required, property, which details the connection error.
because you can access MySQL databases on any
− The $conn object is used in the following examples to
computer connected to your PHP installation, and
access the MySQL database. The die function is good
that potentially includes any host anywhere on the
to use when you are developing PHP code.
Web.
− We are working locally on our own system, therefore 5.2.4 Building and Executing a Query
in place by specifying a domain such as
Web Based Application Development using PHP (MSBTE) 5-14 Database Operations

− It is very simple to send a query from PHP to MySQL − Example : Fetching results one cell at a time
BY using the query method of a connection object.
<?php
The example shows you how to use it.
require_once 'login.php';
− Example. Querying a database with mysqli
$conn = new mysqli($hn, $un, $pw, $db);
<?php
if ($conn->connect_error) die($conn-
$query = "SELECT * FROM student"; >connect_error);
$result = $conn->query($query); $query = "SELECT * FROM student";
if (!$result) die($conn->error); $result = $conn->query($query);
?> if (!$result) die($conn->error);
− Here the variable $query is assigned a string $rows = $result->num_rows;
containing the query to be made, and then passed to for ($j = 0 ; $j < $rows ; ++$j)
the query method of the $conn object, which returns
a result that we place in the object $result.
{
$result->data_seek($j);
− If $result is FALSE, there was a problem and the error
property of the connection object will contain the echo 'Roll No.: ' . $result->fetch_assoc()['rollno'] .
details, so the die function is called to display that '<br/>';
error. $result->data_seek($j);
− All the data returned by MySQL is now stored in an echo 'Name: ' . $result->fetch_assoc()['name'] .
easily interrogatable format in the $result object. '<br/>';
$result->data_seek($j);
5.2.5 Fetching a result
echo 'Percentage: ' . $result-
− Once you have an object returned in $result, you can >fetch_assoc()['percent'] . '<br/><br/>';
use it to extract the data you want, one item at a }
time, using the fetch_assoc() method of the object.
$result->close();
− Example combines and extends the previous
$conn->close();
examples into a program that you can type and run
yourself to retrieve these results. ?>
− I suggest that you save this script using the filename
sample1.php.
Web Based Application Development using PHP (MSBTE) 5-15 Database Operations

− Here, to seek to the correct row each time around the $result = $conn->query($query);
loop, we call the data_seek method of $result before if (!$result) die($conn->error);
fetching each item of data.
$rows = $result->num_rows;
− Then we call the fetch_assoc method to retrieve the
for ($j = 0 ; $j < $rows ; ++$j)
value stored in each cell, and output the result using
echo statements. {

− You will probably agree that all this data seeking is $result->data_seek($j);
rather cumbersome and that there ought to be a $row = $result->fetch_array(MYSQLI_ASSOC);
more efficient method of achieving the same result.
echo 'Roll No.: ' . $row['rollno'] . '<br/>';
− And, indeed, there is a better method, which is to echo 'Name: ' . $row['name'] . '<br/>';
extract a row at a time.
echo 'Percentage: ' . $row['percent'] . '<br/><br/>';
5.2.6 Fetching a Row : }
− To fetch one row at a time, fetch_array() method is $result->close();
used to fetched each row entirety at a time. $conn->close();
− This returns a single row of data as an array, which is ?>
then assigned to the array $row.
MYSQLI_NUM
− The fetch_array() method can return three types of
array according to the value passed to it: − Numeric array. Each column appears in the array in
the order in which you defined it when you created
− Example. Fetching results one row at a time using (or altered) the table.
fetch_array() method.
− In our case, the zeroth element of the array contains
<?php the Author column, element 1 contains the Title, and
require_once 'login.php'; so on.
$conn = new mysqli($hn, $un, $pw, $db); MYSQLI_ASSOC
if ($conn->connect_error) die($conn- Associative array. Each key is the name of a column.
>connect_error); Because items of data are referenced by column name
$query = "SELECT * FROM student"; (rather than index number), use this option where possible
inyour code to make debugging easier and help other
Web Based Application Development using PHP (MSBTE) 5-16 Database Operations

programmers better manage your code. − For example a student data is inserted into a table
MYSQLI_BOTH using INSERT INTO statement.

Associative and numeric array. <?php

Associative arrays are usually more useful than require_once 'login.php';


numeric ones because you can refer to each column by
$conn = new mysqli($hn, $un, $pw, $db);
name, such as $row['author'], instead of trying to
remember where it is in the column order. So this script if ($conn->connect_error) die($conn-
uses an associative array, leading us to pass >connect_error);
MYSQLI_ASSOC. $query = "INSERT INTO
5.2.7 Closing a connection student(rollno,name,percent) VALUES
('CO103','Yogita Khandagale',98.45)";
− PHP will eventually return the memory it has
allocated for objects after you have finished with the $result = $conn->query($query);
script, so in small scripts, you don’t usually need to if (!$result) die ("Database access failed: " .
worry about releasing memory yourself.
$conn->error);
− However, if you are allocating a lot of result objects or
?>
fetching large amounts of data, it can be a good idea
to free the memory you have been using to prevent − The most efficient way to populate MySQL with data
problems later in your script. is to create an arrayand insert the data with a single
− This becomes particularly important on higher-traffic query.
pages, because the amount of memory consumed in a
session can rapidly grow.

− Therefore, note the calls to the close methods of the


5.3.2 Retrieving the Query Result
objects $result and $conn in the preceding scripts, as
soon as each object is no longer needed, like this: − The data can be retrieved from the table using
SQL SELECT statement which is used to select the
$result->close();
records from database tables.
$conn->close();
− SQL query using the SELECT statement will be
executed by passing this SQL query to the PHP
5.3 Database Operations
query() function to retrieve the table data.

− For example data from the student table can be


5.3.1 Insert Operation
executed by using the SELECT statement.
− Data can be inserted into an existing database table − select_sample.php
with an INSERT INTO query.
<?php
− SQL query using the INSERT INTO statement with
require_once 'login.php';
appropriate values, after that we will execute this
$conn = new mysqli($hn, $un, $pw, $db);
insert query through passing it to the
PHP query() function to insert data in table. if ($conn->connect_error) die($conn-
>connect_error);
Web Based Application Development using PHP (MSBTE) 5-17 Database Operations

$query = "SELECT * FROM student"; $row = $result->fetch_array(MYSQLI_NUM);


$result = $conn->query($query); echo "<tr>";
if (!$result) die ("Database access failed: " . for ($k = 0 ; $k < 3 ; ++$k) echo
$conn->error); "<td>$row[$k]</td>";
$rows = $result->num_rows; echo "</tr>";
echo "<table border='1'><tr><th>Roll }
No.</th><th>Name</th><th>Percentage</th></tr>";
echo "</table>";
for ($j = 0 ; $j < $rows ; ++$j)
?>
{
$result->data_seek($j);

− This code simply issues the MySQL query SELECT * FROM student and then displays allthe rows returned. Its output is
as follows :

5.3.3 Update Operation $conn = new mysqli($hn, $un, $pw, $db);


if ($conn->connect_error) die($conn-
− The UPDATE statement is used to change or modify >connect_error);
the existing records in a database table.
$query = "UPDATE student SET percent=98.99
− UPDATE statement is typically used in conjugation WHERE rollno='CO101'";
with the WHERE clause to apply the changes to only $result = $conn->query($query);
those records that matches specific criteria.
if (!$result) die ("Database access failed: " .
− SQL query will be formed using $conn->error);
the UPDATE statement and WHERE clause, after that
?>
a query will be executed by passing it to the
PHPquery() function to update the tables records.
− For example percentage of roll no. C101 will be
updated to ’98.99’ from student table by using 5.3.4 Delete Operations
UPDATE statement.
− Record scan be deleted from a table using the
<?php SQL DELETE statement.
require_once 'login.php';
Web Based Application Development using PHP (MSBTE) 5-18 Database Operations

− DELETE statement is typically used in conjugation with Q. 1 What is the purpose of the semicolon in
the WHERE clause to delete only those records that MySQL queries?
matches specific criteria or condition. Q. 2 Explain field types of MySQL
− SQL query is formed using the DELETE statement Q. 3 Which command would you use to view the
and WHERE clause, after that will be executed by available databases or tables?
passing this query to the PHP query() function to Q. 4 How can you view the structure of a table?
delete the tables records.
Q. 5 Using the SELECT...WHERE construct, how
− For example a student record with a roll no. ‘CO103’ would you return only rows containing the
will be deleted by using DELETE statement and word Langhorne somewhere in the author
WHERE clause. column of the classics table used in this
chapter?
<?php
Q. 6 How do you connect to a MySQL database
require_once 'login.php'; using mysqli?
$conn = new mysqli($hn, $un, $pw, $db); Q. 7 How do you connect mysql database
with PHP ?
if ($conn->connect_error) die($conn-
>connect_error); Q. 8 How do you submit a query to MySQL using
mysqli?
$query = "DELETE from student WHERE
rollno='CO103'"; Q. 9 How can you retrieve a string containing an
error message when a mysqli error occurs?
$result = $conn->query($query);
Q. 10 How can you determine the number of rows
if (!$result) die ("Database access failed: " .
returned by a mysqli query?
$conn->error);
Q. 11 How can you retrieve a particular row of data
?> from a set of mysqli results?
Q. 12 What negative effects can happen if you do
− Example : Removing roll id CO103 from the student not close the objects created by mysqli
methods?
table
Q. 13 List types of MySQL databases
<?php
Q. 14 Write the PHP code for fetching the data from
require_once 'login.php'; a database to webpage?
$conn = new mysqli($hn, $un, $pw, $db); Q. 15 What is difference between
if ($conn->connect_error) die($conn- mysql_fetch_object and mysql_fetch_array ?
>connect_error); Q. 16 Write use of mysql_fetch_row() and
$query = "DELETE from student WHERE mysql_fetch_array() command
rollno='CO103'"; Q. 17 Explain mysql_num_rows and mysql_selectdb
$result = $conn->query($query); command.

if (!$result) die ("Database access failed: " . Q. 18 Explain mysql_fetch_array() function.


$conn->error); Q. 19 Implement Database connectivity. Write a
?> program to insert, update and delete an
element from database.
Q. 20 Describe mysql_connect() function of MySQL
Questions database using PHP.
Q. 21 Write PHP script to select records in table of
MySQL database
Web Based Application Development using PHP (MSBTE) 5-19 Database Operations

Q. 22 Write PHP script to update record in table of Q. 27 Explain use of query string with example in
MySQL database PHP.
Q. 23 Write PHP script to delete records in table of Q. 28 Write a PHP script to insert one record in
MySQL database student registration table ( roll_no, name, city,
mobile_no) in MySQL database.
Q. 24 List storage engine in MySQL. Explain any
one Q. 29 Write a PHP script to read Account
information for customer name, account_no,
Q. 25 Explain mysql_fetch_array() function account_type, branch_name, city, amount
Q. 26 Write a PHP Script to display all the records of from Account table and display all this
students (Name, Address, Class, Semester) information in table format on output screen.
from MySQL table std_info in table format. Account table is in MySQL database
.
❑❑❑

You might also like