0% found this document useful (0 votes)
30 views14 pages

Unit-5 Working With Database in PHP

Php

Uploaded by

carpluswebsite
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)
30 views14 pages

Unit-5 Working With Database in PHP

Php

Uploaded by

carpluswebsite
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

Unit – 5: Working with Database in PHP

Database:
 A database management system(DBMS) is system software for creating and
managing database.
 The DBMS provides users and programmers with a systematic way to create,
retrieve, update and manage data.
 Now-a-days, we use relational database management systems (RDBMS) to store
and manage huge volume of data. This is called relational database because all
the data is stored into different tables and relations are established using
primary keys or foreign keys.
 A Relational Database Management System(RDBMS) is a software that:
 Enables you to implement a database with tables, columns and indexes.
 Guarantees the Referential Integrity between rows of various tables.
 Updates the indexes automatically.
 Interprets an SQL query and combines information from various tables.

RDBMS Terminology
 Database: A database is a collection of tables, with related data.
 Table: A table is a collection of data elements organized in terms of rows and
columns.
 Column: In relational table, a column is a set of value of a particular type.
 Row: A row (tuple or record) is a group of related data.
 Redundancy: Redundancy means having multiple copies of same data in the
database.
 PrimaryKey: A primary key is used to uniquely identify the table record and
cannot contain duplicate data and null value.
 ForeignKey: A foreign key is used to derive value from primary key of other
table.
 Composite key: A composite key is a combination of two or more columns in a
table that can be used to uniquely identify each row in the table.
 Index: A database index is a data structure that improves the speed of operations
in a table.

What is phpMyAdmin?
 Php MyAdmin is one of the most popular applications for MySQL databases
management.
 It is a free tool written in PHP.
 Through this software you can create, alter, drop, delete, import and export
MySQL database tables.
 You can run MySQL queries, optimize, repair and check tables, change collation
and execute other database management commands.

What is MySQL database? OR Introduction of MySQL Database


 MySQL is a freely available open source Relational Database Management System
(RDBMS) that uses Structured Query Language (SQL).
 SQL is the most popular language for adding, accessing and managing content in
a database.
 Standard SQL commands, such as CREATE, DROP, INSERT, and UPDATE can be
used with MySQL.
 MySQL can be used for a variety of applications, but is most commonly found on
Web servers.
 A website that uses MySQL may include Web pages that access information from
a database. These pages are often referred to as “dynamic” meaning the content
of each page is generated from a database as the page loads.
 Websites that use dynamic Web pages are often referred to as database-driven
websites.
 Many database-driven websites that use MySQL also use a Web scripting
language like PHP to access information from the database.
 MySQL commands can be incorporated into the PHP code, allowing part or all of
a Web page to be generated from database information. Because both MySQL and
PHP are both open source (meaning they are free to download and use), the
PHP/MySQL combination has become a popular choice for database-driven
websites.

Creating Database using php myadmin


 Step1: Go to php myadmin: Open your browser and type
http://localhost/phpmyadmin/ You will get following window,

Prepared By: Prof. Amit Rathod Page No.2


 Step2: Select Database menu item: Click on Database Menu where we marked.

 Step3: Create Database: Type your database name, then click ‘create’ Button.

 Step4: Database ending: Your database is created. You can find that one on left
side.

Prepared By: Prof. Amit Rathod Page No.3


Creating Database using Console
 Login to the MySQL server from the command line with the following
command:
mysql –u root -p
 In this case, specified the user root with the –u flag, and then used the –p flag so
MySQL prompts for a password. Enter your current password to complete the
login.
 You should now be at a MySQL prompt that looks very similar to this:
mysql>
 To create a database with the name test type the following command:
CREATE DATABASE test;

Datatypes (field types) of MySQL


 MySQL uses many different data types broken in to three categories:
1) Numeric
2) Date and Time
3) String Types

1) Numeric:
Type Use For Size
A very small integer The signed range is - 128 to 127.
TINY INT
The unsigned range is - 0 to 255.
A small integer The signed range is - 32768 to 32767.
SMALL INT
The unsigned range is O to 65535.
A medium sized The signed range is -8388608 to
MEDIUM
integer 8388607.
INT
The unsigned range is O to 16777215.
A normal sized The signed range is – 2147483648
integer to 2147483647.
INT
The unsigned range is 0 to
4294967295.
A large integer The signed range is -
9223372036854775808 to
BIGIN 9223372036854775807.
The unsigned range is 0 to
18446744073709551615.

Prepared By: Prof. Amit Rathod Page No.4


2) Date and Time:
Type Description Example
A date in YYYY -MM-DD December 30th, 1973 would
DATE format, between 1000- be stored as 1973-12-30.
01-01 and 9999-12-31.
A date and time 3:30 in the afternoon on
combination in YYYY- December 30th , 1973 would
MM-DD HH:MM:SS be stored as 1973-12-30
DATETIME
format, between 1000- 15:30:00.
01-01 00:00:00 and
9999-12-31 23:59:59.
A timestamp between This looks like the previous
midnight, January 1st, DATE TIME format, only
1970 and sometime in without the hyphens between
2037. numbers; 3:30 in the
TIMESTAMP
afternoon on December 30th,
1973 would be stored
As 19731230153000
(YYYYMMDDHHMMSS).
Stores the time in a 02:20:34.
TIME
HH:MM:SS format.
Stores a year in a 2-digit If the length is specified as 2 (for
or a 4-digit format. example YEAR(2)),
YEAR can be between 1970 to
YEAR 2069 (70 to 69). If the length is
specified as 4, then YEAR can be
1901 to 2155. The default length
is 4.

Prepared By: Prof. Amit Rathod Page No.5


3) String Type
Type Description
 A fixed-length string between 1 and 255 characters in
CHAR
length (for Example CHAR (5)). Defining a length is not
(size)
required, but the default is1.
 A variable-length string between 1 and 255 characters
in length. For example, VARCHAR (25). You must define
VARCHAR
a length when creating a VARCHAR field. If you put a
(size)
greater value than 255 it will be converted to a TEXT
type.
 A field with a maximum length of 65535 characters.
TEXT  Fields defined as TEXT also hold large amounts of data.
 TEXT is case insensitive when sorting and comparing.
 BLOB is equal to a text field.
BLOB  A field with a maximum length of 65535 characters.
 BLOB is case sensitive when sorting and comparing.
 It is used for listing. When defining an ENUM, you are
creating a list of items from which the value must be
selected (or it can be NULL).
ENUM  For example, if you wanted your field to contain "A" or
"B" or "C", you would define your ENUM as ENUM
('A','B','C') and only those values(or NULL) could ever
populate that field.

Types of MySQL tables and storage Engine.


 There are two different types of tables:
A) Transaction – safe tables (TSTs):
 Transaction-safe tables allow lost data to be recovered, or a rollback of
data to revert changes recently made.
B) Non-transaction – safe tables (NTSTs)
 Non-transaction – safe tables are much faster and require much less
memory to process updates, but changes are permanent.
 MySQL supports several types of tables and storage engines, each with its own
advantages and disadvantages.
 Here are the most common ones:

Prepared By: Prof. Amit Rathod Page No.6


1) InnoDB:
 The default storage engine is MySQL 5.5 and later versions.
 Supports transactions and foreign keys.
 Provides row-level locking, which improve concurrency. (InnoDB
implements standard row-level locking where there are two types of locks,
shared(S) locks and exclusive (X) locks. A shared (S) lock permit the
transaction that holds the lock to read a row. an exclusive (X) lock permits
the transaction that holds the lock to update or delete row. )
 Uses a clustered index to store data, which can improve performance for
some types of queries.
2) MyISAM: (Index Sequential Access Method)
 The default storage engine in MySQL 5.1 and earlier versions.
 Does not support transaction or foreign keys.
 Provides table-level locking, which can limit concurrency. (MySQL uses
table-level locking for MyISAM, MEMORY, and MERGE tables, permitting
only one session to update those tables at a time. This locking level makes
these storage engines more suitable for read-only, read-mostly, or single-
user applications. )
 Uses a non-clustered index to store data, which can be slower for some
types of queries.
3) MEMORY(or HEAP):
 Stores data in memory rather than on disk.
 Supports table-level locking only.
 Can be useful for caching frequently accessed data or for storing temporary
data that does not need to persist across sessions.
4) CSV:
 Stores data in comma-separated values (CSV) format.
 Can be useful for exchanging data with other applications that support CSV
format.
 Does not support indexes, transactions, or foreign keys.
5) ARCHIVE:
 Stores data in a highly compressed format.
 Can be useful for storing large amounts of data that is rarely accessed.
 Does not support indexes or transactions, but does support foreign keys.
6) NDB (or NDBCLUSTER):
 A distributed storage engine that uses a cluster of MySQL servers to store
data.
 Provides high availability and scalability.
 Supports transactions and foreign keys.
 Uses a distributed index to store data, which can improve performance for
some types of queries.
Prepared By: Prof. Amit Rathod Page No.7
 When creating a table in MySQL, you can specify the storage engine to use for the
table.
 Example:
CREATE TABLE demo
{
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL
} ENGINE=InnoDB;
 this statement creates table called “demo” with columns for id, name, and email,
and specifies that the table should use the InnoDB storage engine.
 if you do not specify a storage engine, MySQL will use the default storage engine
for your version of MySQL.
 You can also change the storage engine for an existing table using the ALTER
TABLE statement.
MySQL Commands:

Integration of PHP with MySQL


 It is possible to execute various commands of MySQLi from PHP.
 PHP provides various built-in functions which allows you to use MySQLi
commands from PHP page. Thus you can integrate PHP with MySQLi.
 Following are the various PHP functions that allows you the facility of
integrating PHP with MySQLi.
1) mysqli_connect()
 The mysqli_connect() function opens a new connection to the MySQLi
server.
 Returns an object representing the connection to the MySQLi server.
 Syntax:
mysqli_connect(server, username, password, databasename)

Parameter Description
Server(host) Specifies a server name.
username Specifies the MySQL username.
password Specifies the MySQL password
Database name The name of MySQL database to use.
 Example:
<?php
/*$host="localhost";
$username="root";
$password="";
$database="db_mydatabase";
Prepared By: Prof. Amit Rathod Page No.8
$conn=mysqli_connect($host,$username,$password,$database);*/
$conn=mysqli_connect("localhost","root"," ", "db_mydatabase ");
if(!$conn)
{
die("Connection Failed:".mysqli_connect_error());
}
else
{
echo "Connected Successfully.....";
mysqli_close($conn);
}
?>
2) mysqli_select_db()
 The mysqli_select_db() function is used to change the default database for
the connection.
 Returns TRUE on success and FALSE on failure.
 Syntax:
mysqli_select_db(connection,databasename)

Parameter Description
connection Required. Connection object name
databasenam Required. Specifies the default database tobe used
 Example e
<?php
$conn=mysqli_connect("localhost","root","");
$databse=mysqli_select_db($conn,"db_mydatabase");
if(!$databse)
{
die("Connection Failed:".mysqli_connect_error());
}
else
{
echo "Connected Successfully.....";
mysqli_close($conn);
}
?>
3) mysqli_query()
 The mysqli_query() function executes a query on a MySQLdatabase.
 Syntax:
mysqli_query(connection,query)

Prepared By: Prof. Amit Rathod Page No.9


Parameter Description
Connection Required. Connection object
query Required.Specifies the querystring
 Example
<?php
$conn=mysqli_connect("localhost","root"," ");
if(!$conn)
{
die("Connection Failed:".mysqli_connect_error());
}
else
{
echo "Connected Successfully.....";

}
$db=mysqli_select_db($conn,"student");
$query="select * from studentinfo";
$result=mysql_query($conn, $query);
if(!$result)
{
echo"Database query failed";
}
mysqli_close($conn);
?>
4) mysqli_num_rows()
 The mysqli_num_rows() function returns the number of rows in a resultset.
 Syntax:
mysqli_num_rows(result)

Parameter Description
result Required. Spec ifies a resultset identifier returned by
mysqli_query()
 Example
<?php
$conn=mysqli_connect("localhost","root",'"');
if(!$conn)
{
die("Connection Failed:".mysqli_connect_error());
}
else
Prepared By: Prof. Amit Rathod Page No.10
{
echo "Connected Successfully.....";

$db=mysqli_select_db($conn,"student");
$query="select * from student info";
$result=mysql_query($conn,$query);
$rowcount=mysqli_num_rows($result);
echo"Total Row:".$rowcount;
mysqli_close($conn);

?>
5) mysqli_fetch_array()
 The mysql_fetch_array () function fetches a result row as an associative
array, a numeric array, or both.
 Returns an array of strings that corresponds to the fetched row.
 NULL if there are no more rows in result-set.
 Syntax:
mysqli_fetch_array(result)

Parameter Description
result Required. Specifies a resultset identifier returned by
mysqli_query()
 Example
<?php
$conn=mysqli_connect("locaIhost","root","");
if(!$conn)
{
die("Connection Failed:".mysqli_connect_error());
}
else
{
echo "Connected Successfully.....";
}
$db=mysql_select_db($conn,"student");
$query="select StudentlD, Name, Email, Gender from studentinfo";
$result=mysqli_query($conn,$qry);
while($row=mysqli_fetch_array($result))
{
echo $row[O]."<br/>";
Prepared By: Prof. Amit Rathod Page No.11
echo $row['Name']."<br/>";
}
?>
 Note: Field names returned from this function are case-sensitive.
6) mysqli_fetch_assoc()
 The mysqli_fetch_assoc() function fetches a result row as an associative
array.
 Returns anassociative array of strings representing the fetched row.
 NULL if there are no more rows in result-set.
 Syntax:
 mysqli_fetch_assoc(result)

Parameter Description
result Required. Specifies a resultset identifier returned by
mysqli_query()
 Example
<?php
$conn=mysqli_connect("locaIhost","root","");
if(!$conn)
{
die("Connection Failed:".mysqli_connect_error());
}
else
{
echo "Connected Successfully.....";
}
$db=mysqli_select_db($conn,"student");
$query="select StudentlD, Name, Email, Gender from studentinfo";
$result=mysqli_query($conn,$query);
while($row=mysqli_fetch_assoc($result)
{
echo $row['StudentlD']."<br/>”;
echo $row['Name']."<br/>";
}
?>
 Note: Field names returned from this function are case-sensitive.
7) mysqli_close()
 The mysqli_close() function closes a previously opened database
connection.
 Syntax:
mysqli_close(connection)

Prepared By: Prof. Amit Rathod Page No.12


Parameter Description
connection Required. Specifies the MySQL connection to close
 Example
<?php
$conn=mysqli_connect("localhost", "root","");
if(!$conn)
{
echo"Could not connect to database";
}
mysqli_close($conn);
?>
8) mysql_error()
 The mysqli_error() function used to get the error message from the last
MySQL operation.
 Syntax:
mysqli_error(connection)

Parameter Description
connection Optional. Before performing any operation on a
MySQL database, it is required to set a connection to
the mysql database you want to work with. And this is
done by mysqli_connect()function.
 Example
 <?php
$conn=mysql_connect("localhost", "root","");
$db=mysql_select_db( "student");
if(!$db)
{
echo "Something else wrong".mysql_error($conn);
die;
}
?>

Hosting Website Using Filezilla Software


 FTP is stands for File Transfer Protocol.
 It is a system that allows you to login to a server and upload, download or modify
content.
 FileZilla is powerful and free software for transferring files over the Internet.

Prepared By: Prof. Amit Rathod Page No.13


 Once you have the FileZilla client downloaded and activated on your computer,
enter the domain name in the address field (you can also use the server’s IP
address).
 The username and the password you need to type in are the same as the ones
you use to login to your cPanel.
 ToConnecttoYourWebServer
1) In the FileZilla Quick Connect bar at the top of the page, enter your Website
URL in the Host field.
2) Enter your FTP username and password (you can leave the Port field blank).
3) Click Quick connect.

 While FileZilla connects to your Webserver, a number of messages display in the


message log.
 Once you've successfully connected to your server, the folder structure of your
server displays in the Remote Site pane in FileZilla.
 To Transfer Your WebSite
1) In the Local Site pane, navigate to the location of your Website.
2) Select the files you want to upload to your Web site. You can select multiple
files by holding down the Ctrl key and clicking on the files you want.
3) Drag the files you want to transfer from the Local Site pane to the Remote Site
pane.
4) FileZilla automatically transfers your files to your Web site.
5) When you are finished uploading your files, close FileZilla and check your
Website in your favorite browser to make sure that your files uploaded
correctly.

Prepared By: Prof. Amit Rathod Page No.14

You might also like