SlideShare a Scribd company logo
1 of 27
Mrs. G.Chandraprabha,M.Sc.,M.Phil.,
Assistant Professor,
Department of Information Technology,
V.V.Vanniaperumal College for Women,
Virudhunagar.
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.
CONNECTING TO A MYSQL
• 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
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
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
INSERTING RECORDS
How to create new database records and insert
them into a table?
INSERT INTO table (field1, field2,...) VALUES (‘value1’, ‘value2’,...)
INSERT INTO table VALUES (‘value1’, ‘value2’,...)
•Alternatively, we have a simplified syntax:
$dbProdRecords = mysql_query("INSERT INTO products
VALUES ( ' ', 'Beer Mug', '600 ml Beer Mug', '100', '5.99')",
$dbLocalhost)
INSERTING RECORDS
Example15-14.php
<?php
// File: example15-15.php
require_once("database2.php");
$dbProdRecords = mysql_query("INSERT INTO products VALUES ('', 'Beer Mug', '600
ml Beer Mug', '100', '5.99')", $dbLocalhost)
or die("Problem writing to table: " . mysql_error());
$dbProdRecords = mysql_query("SELECT * FROM products", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
while ($arrProdRecords = mysql_fetch_array($dbProdRecords)) {
echo "<p>" . $arrProdRecords["Id"] . " ";
echo $arrProdRecords["Name"] . " ";
echo $arrProdRecords["Description"] . " ";
echo $arrProdRecords["Quantity"] . " ";
echo $arrProdRecords["Cost"] . "</p>";
}
?>
DELETING RECORDS
How to delete database records from tables?
DELETE FROM table WHERE field=‘value’
e.g.
$dbCustRecords = mysql_query("DELETE FROM customers
WHERE Id='3'", $dbLocalhost)
Note: If you have a relational database, you should tidy-up the other tables, based on
their connection with the record you’ve deleted.
DELETING RECORDS
How to delete database records from tables?
DELETE FROM table
This will delete all records from a table!
Note: back-up your database first!
AMENDING RECORDS
How to modify the contents of an existing
database record?
UPDATE table SET field=‘value1’, field=‘value2’...WHERE
field=‘value’
• requires you to specify the table, the list of fields with their
updated values, and a condition for selection (WHERE).
AMENDING RECORDS
Example15-14.php
<?php
// File: example15-18.php
require_once("database2.php");
$dbCustRecords = mysql_query("UPDATE products SET Description='250 ml Tall
Glass' WHERE Id='6'", $dbLocalhost)
or die("Problem updating table: " . mysql_error());
$dbProdRecords = mysql_query("SELECT * FROM products", $dbLocalhost)
or die("Problem reading table: " . mysql_error());
while ($arrProdRecords = mysql_fetch_array($dbProdRecords)) {
echo "<p>" . $arrProdRecords["Id"] . " ";
echo $arrProdRecords["Name"] . " ";
echo $arrProdRecords["Description"] . " ";
echo $arrProdRecords["Quantity"] . " ";
echo $arrProdRecords["Cost"] . "</p>";
}
?>
AMENDING RECORDS
How to modify the contents of an existing
database record?
$dbCustRecords = mysql_query("UPDATE products SET Name='Beer
and Lager Glass' WHERE Name='Beer Glass'", $dbLocalhost)
•A number of records will be updated in this example.
Another Example:
UPDATE table SET field=‘value1’, field=‘value2’...WHERE
field=‘value’
COUNTING THE NUMBER OF RECORDS
How to count the number of records after
running a query?
$dbProdRecords = mysql_query("SELECT * FROM products",
$dbLocalhost)
or die("Problem reading table: " . mysql_error());
$intProductCount = mysql_num_rows($dbProdRecords);
• you can also use the same function to determine if a record
exists.
Thank You
Example15-21.php

More Related Content

What's hot

What's hot (20)

Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
 
Xml
XmlXml
Xml
 
PHP - Introduction to File Handling with PHP
PHP -  Introduction to  File Handling with PHPPHP -  Introduction to  File Handling with PHP
PHP - Introduction to File Handling with PHP
 
Loops PHP 04
Loops PHP 04Loops PHP 04
Loops PHP 04
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Files in php
Files in phpFiles in php
Files in php
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
4.2 PHP Function
4.2 PHP Function4.2 PHP Function
4.2 PHP Function
 
Php forms
Php formsPhp forms
Php forms
 
Er model ppt
Er model pptEr model ppt
Er model ppt
 
Sessions in php
Sessions in php Sessions in php
Sessions in php
 
Php basics
Php basicsPhp basics
Php basics
 
Php array
Php arrayPhp array
Php array
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 

Similar to MYSQL - PHP Database Connectivity

Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
WrushabhShirsat3
 

Similar to MYSQL - PHP Database Connectivity (20)

PHP and MySQL.pptx
PHP and MySQL.pptxPHP and MySQL.pptx
PHP and MySQL.pptx
 
Php summary
Php summaryPhp summary
Php summary
 
PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part II
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
 
MYSQL-Database
MYSQL-DatabaseMYSQL-Database
MYSQL-Database
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
unit-ii.pptx
unit-ii.pptxunit-ii.pptx
unit-ii.pptx
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
 
MySQL with PHP
MySQL with PHPMySQL with PHP
MySQL with PHP
 
PHP and Mysql
PHP and MysqlPHP and Mysql
PHP and Mysql
 
AZMS PRESENTATION.pptx
AZMS PRESENTATION.pptxAZMS PRESENTATION.pptx
AZMS PRESENTATION.pptx
 
Sql
SqlSql
Sql
 
MySQL for beginners
MySQL for beginnersMySQL for beginners
MySQL for beginners
 
Python with MySql.pptx
Python with MySql.pptxPython with MySql.pptx
Python with MySql.pptx
 
LECTURE NOTES.pdf
LECTURE NOTES.pdfLECTURE NOTES.pdf
LECTURE NOTES.pdf
 
LECTURE NOTES.pdf
LECTURE NOTES.pdfLECTURE NOTES.pdf
LECTURE NOTES.pdf
 
Php 2
Php 2Php 2
Php 2
 
Python database access
Python database accessPython database access
Python database access
 
Database Basics and MySQL
Database Basics and MySQLDatabase Basics and MySQL
Database Basics and MySQL
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 

More from V.V.Vanniaperumal College for Women

More from V.V.Vanniaperumal College for Women (20)

Control Memory.pptx
Control Memory.pptxControl Memory.pptx
Control Memory.pptx
 
ADDRESSING MODES.pptx
ADDRESSING MODES.pptxADDRESSING MODES.pptx
ADDRESSING MODES.pptx
 
Data_Transfer&Manupulation Instructions.pptx
Data_Transfer&Manupulation Instructions.pptxData_Transfer&Manupulation Instructions.pptx
Data_Transfer&Manupulation Instructions.pptx
 
Timing & Control.pptx
Timing & Control.pptxTiming & Control.pptx
Timing & Control.pptx
 
Human Rights - 1.pptx
Human Rights - 1.pptxHuman Rights - 1.pptx
Human Rights - 1.pptx
 
Registers.pptx
Registers.pptxRegisters.pptx
Registers.pptx
 
Instruction Codes.pptx
Instruction Codes.pptxInstruction Codes.pptx
Instruction Codes.pptx
 
Features of Java.pptx
Features of Java.pptxFeatures of Java.pptx
Features of Java.pptx
 
JVM.pptx
JVM.pptxJVM.pptx
JVM.pptx
 
Constructors in JAva.pptx
Constructors in JAva.pptxConstructors in JAva.pptx
Constructors in JAva.pptx
 
IS-Crypttools.pptx
IS-Crypttools.pptxIS-Crypttools.pptx
IS-Crypttools.pptx
 
IS-Delibrate software attacks.pptx
IS-Delibrate software attacks.pptxIS-Delibrate software attacks.pptx
IS-Delibrate software attacks.pptx
 
IS-Nature of forces.ppt
IS-Nature of forces.pptIS-Nature of forces.ppt
IS-Nature of forces.ppt
 
IS-cryptograpy algorithms.pptx
IS-cryptograpy algorithms.pptxIS-cryptograpy algorithms.pptx
IS-cryptograpy algorithms.pptx
 
IS-Types of IDPSs.pptx
IS-Types of IDPSs.pptxIS-Types of IDPSs.pptx
IS-Types of IDPSs.pptx
 
IS-honeypot.pptx
IS-honeypot.pptxIS-honeypot.pptx
IS-honeypot.pptx
 
Sum of subset problem.pptx
Sum of subset problem.pptxSum of subset problem.pptx
Sum of subset problem.pptx
 
M-coloring.pptx
M-coloring.pptxM-coloring.pptx
M-coloring.pptx
 
storm.ppt
storm.pptstorm.ppt
storm.ppt
 
storm for RTA.pptx
storm for RTA.pptxstorm for RTA.pptx
storm for RTA.pptx
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Recently uploaded (20)

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

MYSQL - PHP Database Connectivity

  • 1. Mrs. G.Chandraprabha,M.Sc.,M.Phil., Assistant Professor, Department of Information Technology, V.V.Vanniaperumal College for Women, Virudhunagar.
  • 2. 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.
  • 3. 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
  • 4. • 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.
  • 5. CONNECTING TO A MYSQL • 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
  • 6. 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.
  • 7. 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.
  • 8. 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.
  • 9. 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.
  • 10. 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.
  • 11. 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.
  • 12. 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.
  • 13. SQL STATEMENT SELECT * FROM customers; • Go and obtain from the database • every field • FROM the • customers table
  • 14. 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)
  • 15. 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.
  • 16. LIMITING THE RECORDS RETURNED SELECT Surname FROM customers •Retrieves only the Surname field from the table customers
  • 17. 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
  • 18. 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
  • 19. INSERTING RECORDS How to create new database records and insert them into a table? INSERT INTO table (field1, field2,...) VALUES (‘value1’, ‘value2’,...) INSERT INTO table VALUES (‘value1’, ‘value2’,...) •Alternatively, we have a simplified syntax: $dbProdRecords = mysql_query("INSERT INTO products VALUES ( ' ', 'Beer Mug', '600 ml Beer Mug', '100', '5.99')", $dbLocalhost)
  • 20. INSERTING RECORDS Example15-14.php <?php // File: example15-15.php require_once("database2.php"); $dbProdRecords = mysql_query("INSERT INTO products VALUES ('', 'Beer Mug', '600 ml Beer Mug', '100', '5.99')", $dbLocalhost) or die("Problem writing to table: " . mysql_error()); $dbProdRecords = mysql_query("SELECT * FROM products", $dbLocalhost) or die("Problem reading table: " . mysql_error()); while ($arrProdRecords = mysql_fetch_array($dbProdRecords)) { echo "<p>" . $arrProdRecords["Id"] . " "; echo $arrProdRecords["Name"] . " "; echo $arrProdRecords["Description"] . " "; echo $arrProdRecords["Quantity"] . " "; echo $arrProdRecords["Cost"] . "</p>"; } ?>
  • 21. DELETING RECORDS How to delete database records from tables? DELETE FROM table WHERE field=‘value’ e.g. $dbCustRecords = mysql_query("DELETE FROM customers WHERE Id='3'", $dbLocalhost) Note: If you have a relational database, you should tidy-up the other tables, based on their connection with the record you’ve deleted.
  • 22. DELETING RECORDS How to delete database records from tables? DELETE FROM table This will delete all records from a table! Note: back-up your database first!
  • 23. AMENDING RECORDS How to modify the contents of an existing database record? UPDATE table SET field=‘value1’, field=‘value2’...WHERE field=‘value’ • requires you to specify the table, the list of fields with their updated values, and a condition for selection (WHERE).
  • 24. AMENDING RECORDS Example15-14.php <?php // File: example15-18.php require_once("database2.php"); $dbCustRecords = mysql_query("UPDATE products SET Description='250 ml Tall Glass' WHERE Id='6'", $dbLocalhost) or die("Problem updating table: " . mysql_error()); $dbProdRecords = mysql_query("SELECT * FROM products", $dbLocalhost) or die("Problem reading table: " . mysql_error()); while ($arrProdRecords = mysql_fetch_array($dbProdRecords)) { echo "<p>" . $arrProdRecords["Id"] . " "; echo $arrProdRecords["Name"] . " "; echo $arrProdRecords["Description"] . " "; echo $arrProdRecords["Quantity"] . " "; echo $arrProdRecords["Cost"] . "</p>"; } ?>
  • 25. AMENDING RECORDS How to modify the contents of an existing database record? $dbCustRecords = mysql_query("UPDATE products SET Name='Beer and Lager Glass' WHERE Name='Beer Glass'", $dbLocalhost) •A number of records will be updated in this example. Another Example: UPDATE table SET field=‘value1’, field=‘value2’...WHERE field=‘value’
  • 26. COUNTING THE NUMBER OF RECORDS How to count the number of records after running a query? $dbProdRecords = mysql_query("SELECT * FROM products", $dbLocalhost) or die("Problem reading table: " . mysql_error()); $intProductCount = mysql_num_rows($dbProdRecords); • you can also use the same function to determine if a record exists.