SlideShare a Scribd company logo
1 of 41
Building Data Dynamic Web Sites
 Truly dynamic web sites
 Content changes over time
 Content customised for individual user
 Content automatically generated
 Content Programmatically generated
 Can be File system based
 HTML and Images stored on File System
 Gets hard to manage over time
 Database based
 HTML, Images etc all generated from database
 Easier to manage
 If data is too large, can overload the database
Database
• Structured collection of data.
• Tables
• Fields
• Query
• Reports
• Essentially a much more sophisticated
implementation of the flat files.
Relational Database
• Stores data in separate tables instead of
a single store.
• Relationships between tables are set
• In theory, this provides a faster, more
flexible database system.
Example
• We wish to maintain a database of student names, IDs, addresses,
and any other information.
• Will be updated frequently with new names and information.
• Will want to retrieve data based on some predicate.
• e.g, ‘give me the names of all Massey students who live in
Albany’.
• Will want to update database with new information about students,
not previously recorded.
• e.g., may decide we want to include IRD nos.
• Very difficult to manage using ‘flat file’ systems
Databases
 Fast, Efficient back end storage
 Easier to manage than file system based approach
 Relational Database structure
 Well developed theory and practise
 Multi-user capable
 Multithreaded, multiprocessor, sometimes cluster
based systems
 Standards based queries
 Structured Query Language (SQL)
MySQL Database
 world's most popular open source database
because of its consistent fast performance, high
reliability and ease of use
 Open Source License:- free
 GNU General Public License
 Free to modify and distribute but all modification must
be available in source code format
 Commercial:- not free
 Fully paid up professional support
• used by Google, Facebook Nokia, YouTube,
Yahoo!, Alcatel-Lucent, Zappos.com, etc.
Basic Database Server Concepts
 Database runs as a server
 Attaches to either a default port or an administrator
specified port
 Clients connect to database
 For secure systems
 authenticated connections
 usernames and passwords
 Clients make queries on the database
 Retrieve content
 Insert content
 SQL (Structured Query Language) is the language used
to insert and retrieve content
• MySQL can be controlled through a
simple command-line interface; however,
we can use phpMyAdmin as an interface
to MySQL.
• phpMyAdmin is a very powerful tool; it
provides a large number of facilities for
customising a database management
system.
Client
Web
browser
Web
server
HTML
Server
MySQL
Operating System
PHP
interpreter
Internet
My codes
HTTP
TCP/IP
• Webserver supports HTTP.
Server: responds
phpMy
Admin
Create Database
Create Table: Customers
Specify the Table’s Fields &
Attributes: Customers
Table Edit Screen: Customers
Table: Products
Table: Products
Insert Record: Customers
Connecting to a MySQL DBMS
• In order for our PHP script to access a
database we need to form a connection
from the script to the database
management system.
resourceId = mysql_connect(server, username, password);
• Server is the DBMS server
• username is your username
• password is your password
Connecting to a MySQL DBMS
• In order for our PHP script to access a
database we need to form a connection
from the script to the database
management system.
resourceId = mysql_connect(server, username, password);
• The function returns a resource-identifier type.
• a PHP script can connect to a DBMS anywhere in the world,
so long as it is connected to the internet.
• we can also connect to multiple DBMS at the same time.
Selecting a database
• Once connected to a DBMS, we can
select a database.
mysql_select_db(databasename, resourceId);
• the resourceId is the one returned by mysql_connect()
• the function returns true if the selection succeeded; false,
otherwise.
Example: Connect to a DBMS and
access database
<?php
$dbLocalhost = mysql_connect("localhost", "root", "")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
echo "<h1>Connected To Database</h1>";
?>
• die() stops execution of script if the database connection
attempt failed.
• mysql_error() returns an error message from the previous
MYSQL operation.
Reading from a database
• We can now send an SQL query to the
database to retrieve some data records.
resourceRecords = mysql_query(query, resourceId);
• the resourceId is the one returned by mysql_connect()
• the function returns a resource identifier to the returned data.
Example: Connect to a DBMS,
access database, send query
<?php
$dbLocalhost = mysql_connect("localhost", "root", "")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
echo "<h1>Connected To Database</h1>";
?>
• the function will return a resource pointer (not the actual
data) to all the records that match the query.
• If all goes well, this script will output nothing on screen.
Extract contents of one record
• We can now extract the actual data from
the resource pointer returned by
mysql_query().
fieldData= mysql_result(resourceRecords, row, field);
• the resourceRecords is the one returned by mysql_query()
• field – database field to return
• the function returns the data stored in the field.
Example: Connect to a DBMS,
access database, send query
<?php
$dbLocalhost = mysql_connect("localhost", "root", "")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
$dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
$strSurname = mysql_result($dbRecords, 0, "Surname");
echo "<p>$strSurname</p>";
?>
• the function will return a resource pointer (not the actual
data) to all the records that match the query.
• If all goes well, this script will output a surname on screen.
SQL statement
SELECT * FROM customers
• Go and obtain from the database
• every field
• FROM the
• customers table
Separating the database
connection
It is worth separating the database
connectivity from our scripts and placing
it in a separate file.
•It provides a convenient means of moving your scripts from
one database platform to another.
Example: Separating the database
connection
<?php
// File: database2.php
$strLocation = "Home";
//$strLocation = "Work";
if ($strLocation == "Home") {
$dbLocalhost = mysql_connect("localhost", "root", "")
or die("Could not connect: " . mysql_error());
mysql_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysql_error());
} else {
$dbLocalhost = mysql_connect("localhost", "username", "password")
or die("Could not connect: " . mysql_error());
mysql_select_db("anotherdatabase", $dbLocalhost)
or die("Could not find database: " . mysql_error());
}
?>
• $strLocation could be easily switched between ‘Home’ or ‘Work’
Viewing a whole record
To view the whole record returned from
mysql_query(), we need another
function...
• resourceRecords – resource identifier returned from
mysql_query().
• it returns an array containing the database record.
array = mysql_fetch_row(resourceRecords)
Example: Displaying all customer
records
<?php
require_once("database2.php");
$dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
while ($arrRecord = mysql_fetch_row($dbRecords)) {
echo "<p>" . $arrRecord[0] . " ";
echo $arrRecord[1] . " ";
echo $arrRecord[2] . " ";
echo $arrRecord[3] . "</p>";
}
?>
• The function returns false when the last record is returned; thus, stopping
the loop.
• Note, however, that the fields are referred to by using numbers – not very
easy to read and mistakes can be introduced.
Limiting the records returned
SELECT Surname FROM customers
•Retrieves only the Surname field from the table customers
Limiting the records returned
SELECT * FROM customers LIMIT 3,4
• Select a certain number of records form a table
• 3 is the starting row
• 4 is the number of records to be selected after the starting
row
Searching for matching records
SELECT * FROM customers WHERE Title=‘Mr’
•The WHERE attribute specifies what to search for within the
database records.
• in this example, only records which have a title of ‘Mr’ will be
returned.
Searching for matching records
SELECT * FROM customers WHERE Title=‘Mr’
OR Title=‘Mrs’
•The WHERE attribute specifies what to search for within the
database records.
• in this example, only records which have a title of ‘Mr’ or
‘Mrs’ will be returned.
• we can also use AND and OR to formulate more
sophisticated conditions.
•
Searching for matching records
SELECT * FROM customers WHERE Title=‘Mr’
AND Surname=‘Smith’ OR Title=‘Mrs’
•The WHERE attribute specifies what to search for within the
database records.
• in this example, only records which have a surname of ‘Smith
and title of ‘Mr’ or the title of ‘Mrs’ will be returned.
• we can also use AND and OR to formulate more
sophisticated conditions.
•
Sorting records
The ORDER BY attribute can be used to sort
the order in which records are obtained.
• the ORDER BY attribute is followed by the data field on
which to sort the record
• DESC or ASC – from high to low, or from low to high
SELECT * FROM cutomers ORDER BY Surname DESC
Accessing Multiple Tables
<?php
// File: example15-13.php
require_once("database2.php");
$dbRecords = mysql_query("SELECT * FROM customers WHERE Title = 'Mrs'", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
echo "<p>Customers:</p>";
while ($arrRecords = mysql_fetch_array($dbRecords)) {
echo "<p>" . $arrRecords["Id"] . " ";
echo $arrRecords["Title"] . " ";
echo $arrRecords["Surname"] . " ";
echo $arrRecords["Firstname"] . "</p>";
}
//...continued...
Accessing Multiple Tables
//continuation...
$dbRecords = mysql_query("SELECT * FROM products WHERE Name = 'Wine Glass'",
$dbLocalhost)
or die("Problem reading table: " . mysql_error());
echo "<p>Products:</p>";
while ($arrRecords = mysql_fetch_array($dbRecords)) {
echo "<p>" . $arrRecords["Id"] . " ";
echo $arrRecords["Name"] . " ";
echo $arrRecords["Description"] . " ";
echo $arrRecords["Quantity"] . " ";
echo $arrRecords["Cost"] . "</p>";
}
?>

More Related Content

Similar to PHP and MySQL.pptx

Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHPTaha Malampatti
 
Data Integration through Data Virtualization (SQL Server Konferenz 2019)
Data Integration through Data Virtualization (SQL Server Konferenz 2019)Data Integration through Data Virtualization (SQL Server Konferenz 2019)
Data Integration through Data Virtualization (SQL Server Konferenz 2019)Cathrine Wilhelmsen
 
AZMS PRESENTATION.pptx
AZMS PRESENTATION.pptxAZMS PRESENTATION.pptx
AZMS PRESENTATION.pptxSonuShaw16
 
Dynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeDynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeClay Helberg
 
Solr Application Development Tutorial
Solr Application Development TutorialSolr Application Development Tutorial
Solr Application Development TutorialErik Hatcher
 
SQL SERVER Training in Pune Slides
SQL SERVER Training in Pune SlidesSQL SERVER Training in Pune Slides
SQL SERVER Training in Pune Slidesenosislearningcom
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytWrushabhShirsat3
 
BITM3730Week14.pptx
BITM3730Week14.pptxBITM3730Week14.pptx
BITM3730Week14.pptxMattMarino13
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowKarsten Dambekalns
 
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdfDBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdfAbhishekKumarPandit5
 
My Database Skills Killed the Server
My Database Skills Killed the ServerMy Database Skills Killed the Server
My Database Skills Killed the ServerColdFusionConference
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web appsIvano Malavolta
 

Similar to PHP and MySQL.pptx (20)

Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Lecture12
Lecture12Lecture12
Lecture12
 
My sql
My sqlMy sql
My sql
 
Data Integration through Data Virtualization (SQL Server Konferenz 2019)
Data Integration through Data Virtualization (SQL Server Konferenz 2019)Data Integration through Data Virtualization (SQL Server Konferenz 2019)
Data Integration through Data Virtualization (SQL Server Konferenz 2019)
 
AZMS PRESENTATION.pptx
AZMS PRESENTATION.pptxAZMS PRESENTATION.pptx
AZMS PRESENTATION.pptx
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Dynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeDynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data Merge
 
Introduction to mysql part 1
Introduction to mysql part 1Introduction to mysql part 1
Introduction to mysql part 1
 
Solr Application Development Tutorial
Solr Application Development TutorialSolr Application Development Tutorial
Solr Application Development Tutorial
 
SQL SERVER Training in Pune Slides
SQL SERVER Training in Pune SlidesSQL SERVER Training in Pune Slides
SQL SERVER Training in Pune Slides
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
unit-ii.pptx
unit-ii.pptxunit-ii.pptx
unit-ii.pptx
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
 
BITM3730Week14.pptx
BITM3730Week14.pptxBITM3730Week14.pptx
BITM3730Week14.pptx
 
Using Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 FlowUsing Document Databases with TYPO3 Flow
Using Document Databases with TYPO3 Flow
 
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdfDBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
DBMS LAB FILE1 task 1 , task 2, task3 and many more.pdf
 
My Database Skills Killed the Server
My Database Skills Killed the ServerMy Database Skills Killed the Server
My Database Skills Killed the Server
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
 
Local storage in Web apps
Local storage in Web appsLocal storage in Web apps
Local storage in Web apps
 

Recently uploaded

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 

Recently uploaded (20)

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 

PHP and MySQL.pptx

  • 1.
  • 2. Building Data Dynamic Web Sites  Truly dynamic web sites  Content changes over time  Content customised for individual user  Content automatically generated  Content Programmatically generated  Can be File system based  HTML and Images stored on File System  Gets hard to manage over time  Database based  HTML, Images etc all generated from database  Easier to manage  If data is too large, can overload the database
  • 3.
  • 4. Database • Structured collection of data. • Tables • Fields • Query • Reports • Essentially a much more sophisticated implementation of the flat files.
  • 5.
  • 6. Relational Database • Stores data in separate tables instead of a single store. • Relationships between tables are set • In theory, this provides a faster, more flexible database system.
  • 7. Example • We wish to maintain a database of student names, IDs, addresses, and any other information. • Will be updated frequently with new names and information. • Will want to retrieve data based on some predicate. • e.g, ‘give me the names of all Massey students who live in Albany’. • Will want to update database with new information about students, not previously recorded. • e.g., may decide we want to include IRD nos. • Very difficult to manage using ‘flat file’ systems
  • 8. Databases  Fast, Efficient back end storage  Easier to manage than file system based approach  Relational Database structure  Well developed theory and practise  Multi-user capable  Multithreaded, multiprocessor, sometimes cluster based systems  Standards based queries  Structured Query Language (SQL)
  • 9. MySQL Database  world's most popular open source database because of its consistent fast performance, high reliability and ease of use  Open Source License:- free  GNU General Public License  Free to modify and distribute but all modification must be available in source code format  Commercial:- not free  Fully paid up professional support • used by Google, Facebook Nokia, YouTube, Yahoo!, Alcatel-Lucent, Zappos.com, etc.
  • 10. Basic Database Server Concepts  Database runs as a server  Attaches to either a default port or an administrator specified port  Clients connect to database  For secure systems  authenticated connections  usernames and passwords  Clients make queries on the database  Retrieve content  Insert content  SQL (Structured Query Language) is the language used to insert and retrieve content
  • 11. • MySQL can be controlled through a simple command-line interface; however, we can use phpMyAdmin as an interface to MySQL. • phpMyAdmin is a very powerful tool; it provides a large number of facilities for customising a database management system.
  • 15. Specify the Table’s Fields & Attributes: Customers
  • 16. Table Edit Screen: Customers
  • 20.
  • 21. Connecting to a MySQL DBMS • In order for our PHP script to access a database we need to form a connection from the script to the database management system. resourceId = mysql_connect(server, username, password); • Server is the DBMS server • username is your username • password is your password
  • 22. Connecting to a MySQL DBMS • In order for our PHP script to access a database we need to form a connection from the script to the database management system. resourceId = mysql_connect(server, username, password); • The function returns a resource-identifier type. • a PHP script can connect to a DBMS anywhere in the world, so long as it is connected to the internet. • we can also connect to multiple DBMS at the same time.
  • 23. Selecting a database • Once connected to a DBMS, we can select a database. mysql_select_db(databasename, resourceId); • the resourceId is the one returned by mysql_connect() • the function returns true if the selection succeeded; false, otherwise.
  • 24. Example: Connect to a DBMS and access database <?php $dbLocalhost = mysql_connect("localhost", "root", "") or die("Could not connect: " . mysql_error()); mysql_select_db("glassesrus", $dbLocalhost) or die("Could not find database: " . mysql_error()); echo "<h1>Connected To Database</h1>"; ?> • die() stops execution of script if the database connection attempt failed. • mysql_error() returns an error message from the previous MYSQL operation.
  • 25. Reading from a database • We can now send an SQL query to the database to retrieve some data records. resourceRecords = mysql_query(query, resourceId); • the resourceId is the one returned by mysql_connect() • the function returns a resource identifier to the returned data.
  • 26. Example: Connect to a DBMS, access database, send query <?php $dbLocalhost = mysql_connect("localhost", "root", "") or die("Could not connect: " . mysql_error()); mysql_select_db("glassesrus", $dbLocalhost) or die("Could not find database: " . mysql_error()); $dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost) or die("Problem reading table: " . mysql_error()); echo "<h1>Connected To Database</h1>"; ?> • the function will return a resource pointer (not the actual data) to all the records that match the query. • If all goes well, this script will output nothing on screen.
  • 27. Extract contents of one record • We can now extract the actual data from the resource pointer returned by mysql_query(). fieldData= mysql_result(resourceRecords, row, field); • the resourceRecords is the one returned by mysql_query() • field – database field to return • the function returns the data stored in the field.
  • 28. Example: Connect to a DBMS, access database, send query <?php $dbLocalhost = mysql_connect("localhost", "root", "") or die("Could not connect: " . mysql_error()); mysql_select_db("glassesrus", $dbLocalhost) or die("Could not find database: " . mysql_error()); $dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost) or die("Problem reading table: " . mysql_error()); $strSurname = mysql_result($dbRecords, 0, "Surname"); echo "<p>$strSurname</p>"; ?> • the function will return a resource pointer (not the actual data) to all the records that match the query. • If all goes well, this script will output a surname on screen.
  • 29. SQL statement SELECT * FROM customers • Go and obtain from the database • every field • FROM the • customers table
  • 30. Separating the database connection It is worth separating the database connectivity from our scripts and placing it in a separate file. •It provides a convenient means of moving your scripts from one database platform to another.
  • 31. Example: Separating the database connection <?php // File: database2.php $strLocation = "Home"; //$strLocation = "Work"; if ($strLocation == "Home") { $dbLocalhost = mysql_connect("localhost", "root", "") or die("Could not connect: " . mysql_error()); mysql_select_db("glassesrus", $dbLocalhost) or die("Could not find database: " . mysql_error()); } else { $dbLocalhost = mysql_connect("localhost", "username", "password") or die("Could not connect: " . mysql_error()); mysql_select_db("anotherdatabase", $dbLocalhost) or die("Could not find database: " . mysql_error()); } ?> • $strLocation could be easily switched between ‘Home’ or ‘Work’
  • 32. Viewing a whole record To view the whole record returned from mysql_query(), we need another function... • resourceRecords – resource identifier returned from mysql_query(). • it returns an array containing the database record. array = mysql_fetch_row(resourceRecords)
  • 33. Example: Displaying all customer records <?php require_once("database2.php"); $dbRecords = mysql_query("SELECT * FROM customers", $dbLocalhost) or die("Problem reading table: " . mysql_error()); while ($arrRecord = mysql_fetch_row($dbRecords)) { echo "<p>" . $arrRecord[0] . " "; echo $arrRecord[1] . " "; echo $arrRecord[2] . " "; echo $arrRecord[3] . "</p>"; } ?> • The function returns false when the last record is returned; thus, stopping the loop. • Note, however, that the fields are referred to by using numbers – not very easy to read and mistakes can be introduced.
  • 34. Limiting the records returned SELECT Surname FROM customers •Retrieves only the Surname field from the table customers
  • 35. Limiting the records returned SELECT * FROM customers LIMIT 3,4 • Select a certain number of records form a table • 3 is the starting row • 4 is the number of records to be selected after the starting row
  • 36. Searching for matching records SELECT * FROM customers WHERE Title=‘Mr’ •The WHERE attribute specifies what to search for within the database records. • in this example, only records which have a title of ‘Mr’ will be returned.
  • 37. Searching for matching records SELECT * FROM customers WHERE Title=‘Mr’ OR Title=‘Mrs’ •The WHERE attribute specifies what to search for within the database records. • in this example, only records which have a title of ‘Mr’ or ‘Mrs’ will be returned. • we can also use AND and OR to formulate more sophisticated conditions. •
  • 38. Searching for matching records SELECT * FROM customers WHERE Title=‘Mr’ AND Surname=‘Smith’ OR Title=‘Mrs’ •The WHERE attribute specifies what to search for within the database records. • in this example, only records which have a surname of ‘Smith and title of ‘Mr’ or the title of ‘Mrs’ will be returned. • we can also use AND and OR to formulate more sophisticated conditions. •
  • 39. Sorting records The ORDER BY attribute can be used to sort the order in which records are obtained. • the ORDER BY attribute is followed by the data field on which to sort the record • DESC or ASC – from high to low, or from low to high SELECT * FROM cutomers ORDER BY Surname DESC
  • 40. Accessing Multiple Tables <?php // File: example15-13.php require_once("database2.php"); $dbRecords = mysql_query("SELECT * FROM customers WHERE Title = 'Mrs'", $dbLocalhost) or die("Problem reading table: " . mysql_error()); echo "<p>Customers:</p>"; while ($arrRecords = mysql_fetch_array($dbRecords)) { echo "<p>" . $arrRecords["Id"] . " "; echo $arrRecords["Title"] . " "; echo $arrRecords["Surname"] . " "; echo $arrRecords["Firstname"] . "</p>"; } //...continued...
  • 41. Accessing Multiple Tables //continuation... $dbRecords = mysql_query("SELECT * FROM products WHERE Name = 'Wine Glass'", $dbLocalhost) or die("Problem reading table: " . mysql_error()); echo "<p>Products:</p>"; while ($arrRecords = mysql_fetch_array($dbRecords)) { echo "<p>" . $arrRecords["Id"] . " "; echo $arrRecords["Name"] . " "; echo $arrRecords["Description"] . " "; echo $arrRecords["Quantity"] . " "; echo $arrRecords["Cost"] . "</p>"; } ?>