PHP OOP
Unit 5: Crud operation using OOP
with PHP
5.1 Introduction to database connection functions.
5.2 Various database queries functions: mysqli_query,
mysqli_fetch_arary / row / object, mysqli_num_rows, mysqli_close,
mysqli_select_db, mysqli_debug
5.3 Implementing CRUD operations with OOP concept.
5.4 Error Handling using ‘try’ and ‘catch’
• 1. mysqli_connect():
As you know, before doing any database related operations, you need
to establish a connection to the MySQL database server. If the
connection is established successfully, then it returns a database
connection resource identifier. If the connection encounters failure,
then it just throws an error.
• 2. mysqli_connect_error():
The MySQLi function throws an error when the connection is not
made successfully and the function stores the error in previous call to
mysqli_connect(). If no error is encountered , it returns NULL. If any
error is encountered , then it returns an error message.
• 3. mysqli_select_db():
This mySQLi function is used to change the default database for
making a connection.
// Change database to "GFG_TEST"
mysqli_select_db($conn,$dbtest);
// PHP code for database "GFG_TEST"...
• 4. mysqli_debug():
Every web developer needs to refer to log files to start
troubleshooting for improving the application performance. The
above mySQLi function is used in the code for all debugging
purposes.
<?php
//create a trace file in the localhost
mysqli_debug("d:t:o,/temp/client.trace");
?>
• mysqli_prepare():
The above MySQLi function is used to prepare a MySQL query for
execution. It returns a statement object for further operations and
returns FALSE if some error occurs.
// prepare the mysql query statement and bind parameters
$query = mysqli_prepare("INSERT INTO items_info (item_name, description) VALUES (?, ?)");
$query->bind_param("ss", $itemname, $description);
// set parameters and execute
$itemname = "Shampoo";
$description = "Hairfall preventing protein shampoo";
$query->execute();
echo "New record inserted successfully";
mysqli_close();
?>
• 7. mysqli_query():
This MySQLi function performs or executes the query on the given
database.
// performs the insert query
mysqli_query($conn,"INSERT INTO items_info
(item_name, description)
VALUES ('Nailpolish', 'Colorbar Pink one')");
echo "Inserted successfully";
• 8. mysqli_rollback():
The mysqli function rollback the current transaction for the given database connection. Turn OFF the
auto-commit, execute the query, then again commit the query and then rollback the current
transaction.
// Set autocommit to off
mysqli_autocommit($conn,FALSE);
// Commit transaction
mysqli_commit($conn);
// Rollback transaction
mysqli_rollback($conn);
• 9. mysqli_fetch_row():
The above MySQLi function is used to fetch one row from the result-
set as an enumerated array. Each call to the above function will return
the next row from the result set. If no rows are fetched, then it
returns FALSE.
Example:
<?php
// Database configuration
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "GFG";
// Create database connection
$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);
$query = "SELECT item_name,description from items_info";
Continue……
if ($result=mysqli_query($conn,$query))
{
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
echo " Item name :".$row[0]." , ";
echo " Description : ".$row[1];
echo nl2br (" \n ");
}//end while
// Free result set
mysqli_free_result($result);
}// end if
mysqli_close($conn);
?>
• 10. mysqli_field_count():
The above MySQLi function is used to return the number of columns
for the most recent query. It returns total number of columns in the
result set.
<?php
// Database configuration
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "GFG";
// Create database connection
$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);
$query = "SELECT * from items_info";
mysqli_query($conn,$query);
$total_columns = mysqli_field_count($conn);
echo $total_columns;
mysqli_close($conn);
?>
• 11. mysqli_fetch_array():
The above MySQLi function is used to fetch a row as an associative,
numeric array or both types of array from the result set.
<?php
// Database configuration
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "GFG";
// Create database connection
$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);
$query = "SELECT item_name,description from items_info";
$result=mysqli_query($conn,$query);
// Gets the Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
echo " Item name :".$row[0];
echo ",";
echo " Description : ".$row[1];
echo nl2br (" \n ");
// Gets the Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
echo " Item name :".$row["item_name"];
echo ",";
echo " Description : ".$row["description"];
// Free the result set
mysqli_free_result($result);
mysqli_close($conn);
?>
• 12. mysqli_fetch_all():
The MySQLi function fetches all rows and return the result set as an
associative array, a numeric array, or both.
<?php
// Database configuration
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "GFG";
// Create database connection
$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);
$query = "SELECT item_name from items_info";
$result = mysqli_query($conn,$query);
$rowcount=mysqli_num_rows($result);
// Gets the Associative array
$row = mysqli_fetch_all($result,MYSQLI_ASSOC);
print_r($row);
for($i=0;$i<$rowcount;$i++)
{
echo "<br> ".$row[$i]['item_name'];
}
// Free the result set
mysqli_free_result($result);
mysqli_close($conn);
?>
• 13. mysqli_free_result():
The above MySQLi function free the memory of the fetched rows of the result set.
if ($result=mysqli_query($conn,$query))
{
while ($row=mysqli_fetch_row($result))
{
echo " Item name :".$row[0].",";
echo " Description : ".$row[1];
echo nl2br (" \n ");
}//end while
// Free result set
mysqli_free_result($result);
}// end if
$
• 14. mysqli_num_rows():
The above MySQLi function is used to return the number of rows of
the result set.
• $rowcount=mysqli_num_rows($result);
• 15. mysqli_affected_rows():
The above MySQLi function is used to return the total number of affected
rows from the previous MySQL SELECT, INSERT, UPDATE, DELETE or
REPLACE query.
// performs the query
mysqli_query($conn,$query);
echo "Total affected
rows :".mysqli_affected_rows($conn);
• 16. mysqli_get_server_info():
The above MySQLi function is used to return the MySQL server version.
// Create database connection
$conn = mysqli_connect($host, $dbuser, $dbpass,
$dbname);
echo "The MySQL server version is".mysqli_get_server_info($conn);
• mysqli_fetch_fields():
The above MySQLi function returns an array of objects which contains the information of columns of
the result set.
if ($result=mysqli_query($conn,$query))
{
// Get the fields
$fields=mysqli_fetch_fields($result);
foreach ($fields as $value)
{
echo "Column name : ".$value->name."<br> ";
echo "Table name : ".$value->table."<br> ";
echo "Maximum length : ".$value->max_length."<br> ";
echo nl2br (" \n ");
}
}
• 18. mysqli_error():
The MySQLi function returns the error message for the last MySQL
function call, if any error exists.
if (!mysqli_query($conn,$query))
{
echo("Error occurred : " .
mysqli_error($conn));
}
• 19. mysqli_autocommit():
This above MySQLi function is used in turning ON/OFF auto-
committing database changes or operations.
• 20. mysqli_error_list():
The MySQLi function returns list of error messages for the last MySQL
function call, if any error exists.
Overview of OOP
• Class − This is a programmer-defined data type, which includes local functions as well as local data. You
can think of a class as a template for making many instances of the same kind (or class) of object.
• Object − An individual instance of the data structure defined by a class. You define a class once and then
make many objects that belong to it. Objects are also known as instance.
• Member Variable − These are the variables defined inside a class. This data will be invisible to the outside
of the class and can be accessed via member functions. These variables are called attribute of the object
once an object is created.
• Member function − These are the function defined inside a class and are used to access object data.
• Inheritance − When a class is defined by inheriting existing function of a parent class then it is called
inheritance. Here child class will inherit all or few member functions and variables of a parent class.
• Parent class − A class that is inherited from by another class. This is also called a base class or super class.
• Child Class − A class that inherits from another class. This is also called a subclass or derived class.
Overview of OOP
• Polymorphism − This is an object oriented concept where same function can be used for
different purposes. For example function name will remain same but it take different number of
arguments and can do different task.
• Overloading − a type of polymorphism in which some or all of operators have different
implementations depending on the types of their arguments. Similarly functions can also be
overloaded with different implementation.
• Data Abstraction − Any representation of data in which the implementation details are hidden
(abstracted).
• Encapsulation − refers to a concept where we encapsulate all the data and member functions
together to form an object.
• Constructor − refers to a special type of function which will be called automatically whenever
there is an object formation from a class.
• Destructor − refers to a special type of function which will be called automatically whenever an
object is deleted or goes out of scope.
class
• Classes are the blueprints of objects. One of the big differences
between functions and classes is that a class contains both data
(variables) and functions that form a package called an: ‘object’.
• Class is a programmer-defined data type, which includes local
methods and local variables.
• Class is a collection of objects. Object has properties and behavior.
<?php
class
person
{
}
?>
<?php
class Books {
/* Member variables */
var $price;
var $title;
/* Member functions */
function setPrice($par){
$this->price = $par;
}
function getPrice(){
echo $this->price ."<br/>";
}
function setTitle($par){
$this->title = $par;
}
function getTitle(){
echo $this->title ." <br/>";
}
}
?>
$physics = new Books;
$maths = new Books;
$chemistry = new Books;
$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );
$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();
Access specifier:
• In the PHP each and every property of a class in must have one of three visibility
levels, known as public, private, and protected.
• Public: Public properties can be accessed by any code, whether that code is
inside or outside the class. If a property is declared public, its value can be read
or changed from anywhere in your script.
• Private: Private properties of a class can be accessed only by code inside the
class. So if we create a property that’s declared private, only methods and
objects inside the same class can access its contents.
• Protected: Protected class properties are a bit like private properties in that they
can’t be accessed by code outside the class, but there’s one little difference in
any class that inherits from the class i.e. base class can also access the properties.
<?php
class GeeksForGeeks
{
public $x = 100 ; # public attributes
public $y = 50 ;
function add()
{
echo $a = $this->x + $this->y ;
echo " ";
}
}
class child extends GeeksForGeeks
{
function sub()
{
echo $s = $this->x - $this->y ;
}
}
$obj = new child;
// It will return the addition result
$obj->add() ;
// It's a derived class of the main class,
// which has a public object and therefore can be
// accessed, returning the subtracted result.
$obj->sub() ;
?>
private $b = 5 ;
private function div() # private member function
{
echo $d = $this->a / $this->b ;
echo " ";
}
}
class child extends GeeksForGeeks
{
function mul()
{
echo $m = $this->a * $this->b ;
}
$obj= new child;
// It's supposed to return the division result
// but since the data and function are private
// they can't be accessed by a derived class
// which will lead to fatal error .
$obj->div();
// It's a derived class of the main class,
echo $d = $this->x / $this->y ;
echo " ";
}
}
class child extends GeeksForGeeks
{
function sub()
{
echo $s = $this->x - $this->y ;
}
}
class derived # Outside Class
{
function mul()
{
echo $m = $this->x * $this->y ;
}
}
$obj= new child;
// It will return the division result
$obj->div();
Multiple Inheritance is the property of the Object Oriented Programming languages in which
child class or sub class can inherit the properties of the multiple parent classes or super
classes.
PHP doesn’t support multiple inheritance but by using Interfaces in PHP or using Traits in PHP
instead of classes, we can implement it.
Traits (Using Class along with Traits): The trait is a type of class which enables multiple
inheritance. Classes, case classes, objects, and traits can all extend no more than one class
but can extend multiple traits at the same time.
Syntax:
class child_class_name extends parent_class_name
{
use trait_name;
... ...
child_class functions }
Link for video
• https://www.youtube.com/watch?v=qPrNNPucukw
• https://www.youtube.com/watch?v=M5f3r-LG7UY
• https://www.youtube.com/watch?v=xx0kxaPRbFc