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

10.DB Part 2

The document covers the management of databases using MySQL and PHP, including concepts like database creation, connection, and manipulation through SQL queries. It explains how to handle database connections, execute SQL statements, and manage errors using object-oriented programming with the mysqli class. Additionally, it discusses techniques for retrieving, filtering, and sorting records from multiple tables.

Uploaded by

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

10.DB Part 2

The document covers the management of databases using MySQL and PHP, including concepts like database creation, connection, and manipulation through SQL queries. It explains how to handle database connections, execute SQL statements, and manage errors using object-oriented programming with the mysqli class. Additionally, it discusses techniques for retrieving, filtering, and sorting records from multiple tables.

Uploaded by

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

Managing data

Summary

• Concept of databases
• Tables and Fields
• Field Types
• phpMyAdmin Tool for manipulating databases
• Creation of a database
• How to add and edit records
• How to back-up a database
• Database Design
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
Working with Database Connections as
Objects
Access MySQL database connections as
objects by instantiating an object from the
mysqli class
To connect to a MySQL database server:
$DBConnect = mysqli_connect("localhost", "dongosselin",
"rosebud", "real_estate");

To connect to the MySQL database server


using object-oriented style:
$DBConnect = new mysqli("localhost", "dongosselin",
"rosebud", "real_estate");
PHP-Object Oriented Programming 5
Instantiating and Closing a MySQL
Database Object
This statement also uses the mysqli()
constructor function to instantiate a
mysqli class object named $DBConnect
$DBConnect = new mysqli("localhost",
"dongosselin","rosebud", "real_estate");

To explicitly close the database connection,


use the close() method of the mysqli
class
$DBConnect->close();

PHP-Object Oriented Programming 6


Selecting a Database

Select or change a database with the


mysqli_select_db() function
Pass two arguments to the
mysqli_select_db() function:
1. The variable representing the database
connection
2. The name of the database you want to use

PHP-Object Oriented Programming 7


Example of procedural syntax to open a
Selecting
connection to a Database
a MySQL (continued)
database server:
$DBConnect = mysqli_connect("localhost", "dongosselin", "rosebud");
mysqli_select_db($DBConnect, "real_estate");
// additional statements that access or manipulate the database
mysqli_close($DBConnect);

An object-oriented version of the code:


$DBConnect = mysqli_connect("localhost", "dongosselin",
"rosebud");
$DBConnect->select_db("real_estate");
// additional statements that access or manipulate the database
$DBConnect->close();

PHP-Object Oriented Programming 8


Handling MySQL Errors

With object-oriented style, you cannot


terminate script execution with the die()
or exit() functions
$DBConnect = @mysqli_connect("localhost",
"dongosselin", "rosebud")
Or die("<p>Unable to connect to the database
server.</p>"
. "<p>Error code " . mysqli_connect_errno()
. ": " . mysqli_connect_error()) . "</p>";

PHP-Object Oriented Programming 9


Handling MySQL Errors
With object-oriented style, check whether a
value is assigned to the
mysqli_connect_errno() or
mysqli_connect_error() functions and
then call the die() function to terminate
script execution
$DBConnect = @new mysqli("localhost", "dgosselin",
"rosebud");
if (mysqli_connect_errno())
die("<p>Unable to connect to the database server.</p>"
. "<p>Error code " . mysqli_connect_errno()
. ": " . mysqli_connect_error()) . "</p>";

PHP-Object Oriented Programming 10


Handling MySQL Errors
For any methods of the mysqli class that
fail (as indicated by a return value of
false), terminate script execution by
appending die() or exit() functions to
method call statements
$DBName = "guitars";
@$DBConnect->select_db($DBName)
Or die("<p>Unable to select the database.</p>"
. "<p>Error code " . mysqli_errno($DBConnect)
. ": " . mysqli_error($DBConnect)) . "</p>";
PHP-Object Oriented Programming 11
Executing SQL Statements

With object-oriented style, use the query()


method of the mysqli class
To return the fields in the current row of a
resultset into an indexed array use:
The mysqli_fetch_row() function
To return the fields in the current row of a
resultset into an associative array use:
The mysqli_fetch_assoc() function

12
Executing SQL Statements
(continued)
$TableName = "inventory";
$SQLstring = "SELECT * FROM inventory";
$QueryResult = $DBConnect->query($SQLstring)
Or die("<p>Unable to execute the query.</p>"
. "<p>Error code “ . $DBConnect->errno
. ": “ . $DBConnect->error) . "</p>";
echo "<table width='100%‘ border='1'>";
echo "<tr><th>Make</th><th>Model</th>
<th>Price</th><th>Inventory</th></tr>";
$Row = $QueryResult->fetch_row();
do {
echo "<tr><td>{$Row[0]}</td>";
echo "<td>{$Row[1]}</td>";
echo "<td align='right'>{$Row[2]}</td>";
echo "<td align='right'>{$Row[3]}</td></tr>";
$Row = $QueryResult->fetch_row(); 13

} while ($Row);
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 = mysqli_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.

mysqli_select_db(databasename, resourceId);

• the resourceId is the one returned by mysqli_connect()


• the function returns true if the selection succeeded; false,
otherwise.
Example: Connect to a
DBMS and access database
<?php
$dbLocalhost = mysqli_connect("localhost", "root", "")
or die("Could not connect: " . mysql_error());
mysqli_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 = mysqli_query(query, resourceId);

• the resourceId is the one returned by mysqli_connect()


• the function returns a resource identifier to the returned data.
Example: Connect to a
DBMS, access database,
<?php send query
$dbLocalhost = mysqli_connect("localhost", "root", "")
or die("Could not connect: " . mysqli_error());
mysqli_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysqli_error());
$dbRecords = mysqli_query("SELECT * FROM customers", $dbLocalhost)
or die("Problem reading table: " . mysqli_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= mysqli_result(resourceRecords, row, field);

• the resourceRecords is the one returned by mysqli_query()


• field – database field to return
• the function returns the data stored in the field.
field
Example: Connect to a
DBMS, access database,
<?php
send query
$dbLocalhost = mysqli_connect("localhost", "root", "")
or die("Could not connect: " . mysqli_error());
mysqli_select_db("glassesrus", $dbLocalhost)
or die("Could not find database: " . mysqli_error());
$dbRecords = mysqli_query("SELECT * FROM customers", $dbLocalhost)
or die("Problem reading table: " . mysqli_error());
$strSurname = mysqli_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 = mysqli_connect("localhost", "root", "")
or die("Could not connect: " . mysqli_error());
mysqli_select_db("glassesrus",
glassesrus $dbLocalhost)
or die("Could not find database: " . mysqli_error());
} else {
$dbLocalhost = mysqli_connect("localhost", "username", "password")
or die("Could not connect: " . mysqli_error());

mysqli_select_db("anotherdatabase",
anotherdatabase $dbLocalhost)
or die("Could not find database: " . mysqli_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...

array = mysqli_fetch_row(resourceRecords)

• resourceRecords – resource identifier returned from


mysqli_query().
• it returns an array containing the database record.
Example: Displaying all customer records

<?php

require_once("database2.php");

$dbRecords = mysqli_query("SELECT * FROM customers", $dbLocalhost)


or die("Problem reading table: " . mysqli_error());

while ($arrRecord = mysqli_fetch_row($dbRecords))


mysqli_fetch_row {
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
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
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
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.
SELECT * FROM cutomers ORDER BY Surname DESC

• 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

Example15-12.php
Accessing Multiple Tables
(1)
<?php
// File: example15-13.php

require_once("database2.php");

$dbRecords = mysqli_query("SELECT * FROM customers WHERE Title = 'Mrs'", $dbLocalhost)


or die("Problem reading table: " . mysqli_error());

echo "<p>Customers:</p>";
while ($arrRecords = mysqli_fetch_array($dbRecords)) {
echo "<p>" . $arrRecords["Id"] . " ";
echo $arrRecords["Title"] . " ";
echo $arrRecords["Surname"] . " ";
echo $arrRecords["Firstname"] . "</p>";
}

//...continued...

Example15-13.php
Accessing Multiple Tables
(2)
//continuation...

$dbRecords = mysqli_query("SELECT * FROM products WHERE Name = 'Wine Glass'",


$dbLocalhost)
or die("Problem reading table: " . mysqli_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>";
}
?>

Example15-13.php
Using records to read another
table
Read a customer record, and then
Read a customer record, and then
show the products purchased by that
customer.
Tables
• Customers
• Products
• Purchases
• PurchaseProducts

Example15-14.php
BIRD’S EYEVIEW

Using records to read another


... table
$strSurname = "Jones";
Jones
$dbCustRecords = mysqli_query("SELECT * FROM customers WHERE Surname =
'$strSurname' ",...)
while ($arrCustRecords = mysqli_fetch_array($dbCustRecords)) { //#1
$intId = $arrCustRecords["Id"];
//display customer’s details
$dbPurRecords = mysqli_query("SELECT * FROM purchases WHERE customers_Id =
'$intId'", ...)
while ($arrPurRecords = mysqli_fetch_array($dbPurRecords)) {//#2
$intPurId = $arrPurRecords["Id"];
//display purchase date
$dbProRecords=mysqli_query("SELECT * FROM purchaseProducts WHERE
purchases_Id='$intPurId' ",..)
while ($arrProRecords = mysqli_fetch_array($dbProRecords)) { //#3
$intProductId = $arrProRecords["products_Id"];
//display Quantity
$dbProductRecords = mysqli_query("SELECT * FROM products WHERE Id =
'$intProductId'",..)
$arrProductRecord = mysqll_fetch_array($dbProductRecords);
//display product details Example15-14.php
} #3
Complete version

Using records to read another


<?php table
require_once("database2.php");

$strSurname = "Jones";
Jones

$dbCustRecords = mysqli_query("SELECT * FROM customers WHERE Surname = '$strSurname'


", $dbLocalhost)
or die("Problem reading table: " . mysqli_error());

while ($arrCustRecords = mysqli_fetch_array($dbCustRecords)) {


$intId = $arrCustRecords["Id"];
echo "<p>Customer: ";
echo $arrCustRecords["Title"] . " ";
echo $arrCustRecords["Surname"] . " ";
echo $arrCustRecords["Firstname"] . "</p>";

$dbPurRecords = mysqli_query("SELECT * FROM purchases WHERE customers_Id = '$intId'",


$dbLocalhost)
or die("Problem reading table: " . mysqli_error());

Example15-14.php
Complete version

Using records to read another


table
while ($arrPurRecords = mysqli_fetch_array($dbPurRecords)) {
$intPurId = $arrPurRecords["Id"];
echo "<p>Purchased On: ";
echo $arrPurRecords["Day"] . "/";
echo $arrPurRecords["Month"] . "/";
echo $arrPurRecords["Year"] . "</p>";

$dbProRecords= mysqli_query("SELECT * FROM purchaseProducts WHERE purchases_Id='$intPurId'


", $dbLocalhost)
or die("Problem reading table: " . mysqli_error());

while ($arrProRecords = mysqli_fetch_array($dbProRecords)) {


$intProductId = $arrProRecords["products_Id"];
echo "<p>" . $arrProRecords["Quantity"] . " ";

$dbProductRecords = mysqli_query("SELECT * FROM products WHERE Id = '$intProductId'",


$dbLocalhost)
or die("Problem reading table: " . mysqli_error());

$arrProductRecord = mysqli_fetch_array($dbProductRecords);
echo $arrProductRecord["Name"] . " (" . $arrProductRecord["Description"] . ") at &#163;";
echo $arrProRecords["Cost"] . " each.</p>";
}
}
} Example15-14.php
Example15-14.php
?>
Inserting records
How to create new database records
and insert them into a table?
INSERT INTO table (field1, field2,...) VALUES (‘value1’, ‘value2’,...)

•Alternatively, we have a simplified syntax:

INSERT INTO table VALUES (‘value1’, ‘value2’,...)

$dbProdRecords = mysql_query("INSERT INTO products


VALUES ( ' ', 'Beer Mug', '600 ml Beer Mug', '100', '5.99')",
$dbLocalhost)

Example15-15.php
Inserting records
<?php
// File: example15-15.php

require_once("database2.php");

$dbProdRecords = mysqli_query("INSERT INTO products VALUES ('', 'Beer Mug', '600


ml Beer Mug', '100', '5.99')", $dbLocalhost)
or die("Problem writing to table: " . mysqli_error());

$dbProdRecords = mysqli_query("SELECT * FROM products", $dbLocalhost)


or die("Problem reading table: " . mysqli_error());

while ($arrProdRecords = mysqli_fetch_array($dbProdRecords)) {


echo "<p>" . $arrProdRecords["Id"] . " ";
echo $arrProdRecords["Name"] . " ";
echo $arrProdRecords["Description"] . " ";
echo $arrProdRecords["Quantity"] . " ";
echo $arrProdRecords["Cost"] . "</p>";
}
?> Example15-14.php
Example15-15.php
Deleting records
How to delete database records from
tables
DELETE FROM table WHERE field=‘value’

e.g.

$dbCustRecords = mysqli_query("DELETE FROM customers


WHERE Id='3'", $dbLocalhost)

Note: If you have a relational database, you should tidy-up the other tables, based o
their connection with the record you’ve deleted.

Example15-16.php
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!

Example15-17.php
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).

Example15-18.php
Amending records
<?php
// File: example15-18.php

require_once("database2.php");

$dbCustRecords = mysqli_query("UPDATE products SET Description='250 ml Tall


Glass' WHERE Id='6'", $dbLocalhost)
or die("Problem updating table: " . mysqli_error());

$dbProdRecords = mysqli_query("SELECT * FROM products", $dbLocalhost)


or die("Problem reading table: " . mysqli_error());

while ($arrProdRecords = mysqli_fetch_array($dbProdRecords)) {


echo "<p>" . $arrProdRecords["Id"] . " ";
echo $arrProdRecords["Name"] . " ";
echo $arrProdRecords["Description"] . " ";
echo $arrProdRecords["Quantity"] . " ";
echo $arrProdRecords["Cost"] . "</p>";
}
?> Example15-14.php
Example15-18.php
Amending records
How to modify the contents of an
existing database record
UPDATE table SET field=‘value1’, field=‘value2’...WHERE
field=‘value’

Another Example:
$dbCustRecords = mysqli_query("UPDATE products SET Name='Beer
and Lager Glass' WHERE Name='Beer Glass'", $dbLocalhost)

•A number of records will be updated in this example.

Example15-19.php
Counting the number of
records
How to count the number of records
after running a query?
$dbProdRecords = mysqli_query("SELECT * FROM products",
$dbLocalhost)
or die("Problem reading table: " . mysqli_error());

$intProductCount = mysqli_num_rows($dbProdRecords);

• you can also use the same function to determine if a record


exists.
Example15-20.php
Example15-21.php
Select a substring
How to count the number of records
after running a query
SELECT * FROM products WHERE substring(Name,1,4)=‘Wine’

•This will return all records from the products table where the
first four characters in the name field equals ‘Wine’

Example15-22.php
End of Lecture

You might also like