You are on page 1of 24

Unit-3

Database applications with MySQL:

MySQL is the most popular open-source database. Some of the


applications to help you create, write, manage, and visualize your
database.

1. TurboDbAdmin
TurboDBAdmin is a free web-based AJAX application that helps you
manage, explore, and edit MySQL and PostgreSQL databases. It gives
you the ability to export your database into a downloadable file which
you can keep as a back up in case you need to restore your database.

2. EMS SQL Manager for MySQL


EMS SQL Manager for MySQL is a first-rate graphical interface tool for
MySQL database administration and development.

3. MySQL GUI Tools


MySQL GUI Tools is a bundle of graphical user interface tools, MySQL
Administrator is a GUI for managing databases and has database
optimization features, rapid back up and restoration of databases, access
to log and error files, and more. 

4. phpMyAdmin
phpMyAdmin is a browser-based MySQL database administration tool
written in PHP. It is personal graphical interface administration tool of
choice because it’s simple to use and has a big list of features and options.
You can easily export a database for back up or migration into another
server environment.

Features of phpMyAdmin
phpMyAdmin supports several features that are given below:

o phpMyAdmin can create, alter, browse, and drop databases, views, tables,
columns, and indexes.
o It can display multiple results sets through queries and stored procedures.
o phpMyAdmin use stored procedure and queries to display multiple results
sets.
o It supports foreign keys and InnoDB tables.
o phpMyAdmin can track the changes done on databases, views, and tables.
o We can also create PDF graphics of our database layout.
o phpMyAdmin can be exported into various formats such as XML, CSV, PDF,
ISO/IEC 26300 - OpenDocument Text and Spreadsheet.
o It supports mysqli, which is the improved MySQL extension.
o phpMyAdmin can interact with 80 different languages.
o phpMyAdmin can edit, execute, and bookmark any SQL-statements and even
batch-queries.
o It provides the facility to backup the database into different forms.

Advantage of phpMyAdmin
o phpMyAdmin can run on any server or any OS as it has a web browser.
o We can easily create, delete, and edit the database and can manage all
elements using the graphical interface of phpMyAdmin, which is much
easier than MySQL command-line editor.
o phpMyAdmin helps us to control the user's permission and operate several
servers at the same time.
o We can also backup our database and export the data into different formats
like XML, CSV, SQL, PDF, OpenDocument Text, Excel, Word, and Spreadsheet,
etc.
o We can execute complex SQL statements and queries, create and edit
functions, triggers, and events using the graphical interface of phpMyAdmin.

Disadvantage of phpMyAdmin
o phpMyAdmin is a simple interface, but quite tough for a beginner to learn.
o phpMyAdmin is difficult to install as it needs three more software tools before
installation, which is- Apache server, PHP, and MySQL.
o We have to install all these software tools individually, whereas XAMPP
already contains them in a single package. XAMPP is the easiest way to get
phpMyAdmin.
o It has no schema visualization.
o phpMyAdmin is a web-based software tool which runs only on the browser, so
It completely depends on browsers.
o It does not have auto-compilation capability.

5. WWW SQL Designer


WWW SQL Designer allows you to model databases via your web
browser. It’s a great way to document your database design, just use the
print screen function key on your keyboard (or your preferred screen-
capturing application), paste it into an image editor or word processing
software, and you’ll have a document of your database model. Once
you’re satisfied with the model, you can auto-generate the MySQL code.
Introduction to MySQL & its applications:
MySQL is an open-source, fast reliable, and flexible relational database management system,
typically used with PHP.

 MySQL is a database system used for developing web-based software applications.


 MySQL used for both small and large applications.
 MySQL is a relational database management system (RDBMS).
 MySQL is fast, reliable, and flexible and easy to use.
 MySQL supports standard SQL (Structured Query Language).
 MySQL is free to download and use.
 MySQL was developed by Michael Widenius and David Axmark in 1994.
 MySQL is presently developed, distributed, and supported by Oracle Corporation.
 MySQL Written in C, C++.

Current users of MySql:

 Some of the most famous websites like Facebook, Wikipedia, Google (not for search),
YouTube, Flickr.
 Content Management Systems (CMS) like WordPress, Drupal, Joomla, phpBB etc.
 A large number of web developers worldwide are using MySQL to develop web
applications.

Regular Expressions
MySQL supports another type of pattern matching operation based on the regular
expressions and the REGEXP operator.

 It provide a powerful and flexible pattern match that can help us implement power search
utilities for our database systems.
 It also supports a number of metacharacters which allow more flexibility and control when
performing pattern matching.
 The backslash is used as an escape character. It’s only considered in the pattern match if
double backslashes have used.
 Not case sensitive.
REGEXP operator: MySQL REGEXP performs a pattern match of a string expression
against a pattern. The pattern is supplied as an argument.

If the pattern finds a match in the expression, the function returns 1, else it returns 0.

If either expression or pattern is NULL, the function returns NULL.

Syntax:
expr REGEXP pat
where expr is a string expression and pat is a  pattern whose match is to be found in the expression.

Pattern What the Pattern matches

* Zero or more instances of string preceding it

+ One or more instances of strings preceding it

. Any single character

? Match zero or one instances of the strings preceding it.

^ caret(^) matches Beginning of string

$ End of string

[abc] Any character listed between the square brackets

[^abc] Any character not listed between the square brackets

[A-Z] match any upper case letter.

[a-z] match any lower case letter

[0-9] match any digit from 0 through to 9.


[[:<:]] matches the beginning of words.

[[:>:]] matches the end of words.

matches a character class i.e. [:alpha:] to match letters, [:space:] to match white
[:class:] space, [:punct:] is match punctuations and [:upper:] for upper class letters.

p1|p2|p3 Alternation; matches any of the patterns p1, p2, or p3

{n} n instances of preceding element

{m,n} m through n instances of preceding element

Examples:

 Match beginning of string(^):


Gives all the names starting with ‘sa’.Example- sam,samarth.
 SELECT name FROM student_tbl WHERE name REGEXP '^sa';

 Match the end of a string($):


Gives all the names ending with ‘on’.Example – norton,merton.
 SELECT name FROM student_tbl WHERE name REGEXP 'on$';

 Match zero or one instance of the strings preceding it(?):


Gives all the titles containing ‘com’.Example – comedy , romantic comedy.
 SELECT title FROM movies_tbl WHERE title REGEXP 'com?';

 matches any of the patterns p1, p2, or p3(p1|p2|p3):


Gives all the names containing ‘be’ or ‘ae’.Example – Abel, Baer.
 SELECT name FROM student_tbl WHERE name REGEXP 'be|ae' ;

 Matches any character listed between the square brackets([abc]):


Gives all the names containing ‘j’ or ‘z’.Example – Lorentz, Rajs.
 SELECT name FROM student_tbl WHERE name REGEXP '[jz]' ;
 Matches any lower case letter between ‘a’ to ‘z’- ([a-z]) ([a-z] and (.)):
Retrieve all names that contain a letter in the range of ‘b’ and ‘g’, followed by any
character, followed by the letter ‘a’.Example – Tobias, sewall.
Matches any single character(.)
SELECT name FROM student_tbl WHERE name REGEXP '[b-g].[a]' ;

 Matches any character not listed between the square brackets.([^abc]):


Gives all the names not containing ‘j’ or ‘z’. Example – nerton, sewall.
 SELECT name FROM student_tbl WHERE name REGEXP '[^jz]' ;

 Matches the end of words[[:>:]]:


Gives all the titles ending with character “ack”. Example – Black.
 SELECT title FROM movies_tbl WHERE REGEXP 'ack[[:>:]]';

 Matches the beginning of words[[:<:]]:


Gives all the titles starting with character “for”. Example – Forgetting Sarah
Marshal.
 SELECT title FROM movies_tbl WHERE title REGEXP '[[:<:]]for';

 Matches a character class[:class:]:


i.e [:lower:]- lowercase character ,[:digit:] – digit characters etc.
Gives all the titles containing alphabetic character only. Example – stranger things,
Avengers.
SELECT title FROM movies_tbl WHERE REGEXP '[:alpha:]' ;

Object Oriented Programming with PHP and MySQL:

Class:
A class is an entity that determines how an object will behave and what the object will
contain. In other words, it is a blueprint or a set of instruction to build a specific type of
object.

In PHP, declare a class using the class keyword, followed by the name of the class and a
set of curly braces ({}).
Syntax to Create Class in PHP
<?php  
class MyClass  
    {  
        // Class properties and methods go here  
    }  
?> 

Object:
A class defines an individual instance of the data structure. We define a class once and
then make many objects that belong to it. Objects are also known as an instance.

An object is something that can perform a set of related activities.

Syntax:

<?php  
class MyClass  
{  
        // Class properties and methods go here  
}  
$obj = new MyClass;  
var_dump($obj);   // var_dump() function is used to display the structured information (type and value) about one or more

variables.

?>  

Example
<?php  
class demo  
{  
        private $a= "hello World!!!!!!!";  
        public function display()  
        {  
        echo $this->a;  
        }  
}  
$obj = new demo();  
    $obj->display();  
?>  
//code for Database connectivity, this file name is connection1.php
<?php

$sname="localhost";

$uname="root";

$pass="";

$dbname="test";

$cn=mysqli_connect( $sname, $uname, $pass);

if(!$cn){

echo("Unable to connect with web server");

die();}

$db=mysqli_select_db($cn, $dbname);

if(!$db)

echo("Unable to connect with web server");

die();

echo("Database connected successfully....");

?>

Note: The die() is an inbuilt function in PHP. It is used to print message and exit from the current
php script.

Mysqli( ): MySQLi is an API used as a connector function to link the backend of the PHP
app to the MySQL database. It works just like the previous version, but it is safer and
faster, and provides a better set of functions and extensions.
//code for inserting data into the Database table using php

//This file name is connection.php

<?php

$server="localhost";

$username="root";

$password="";

$dbname="test";

$conn=mysqli_connect($server,$username, $password,$dbname);

if (isset($_POST['submit']))

if(!empty($_POST['name']) && !empty($_POST['email']) && !


empty($_POST['age']) && !empty($_POST['address']))

$name=$_POST['name'];

$email=$_POST['email'];

$age=$_POST['age'];

$address=$_POST['address'];

$query="insert into student (name, email, age, address) values ('$name',


'$email', '$age', '$address')";

$run=mysqli_query($conn, $query) or die(mysqli_error());

if($run)

{echo("Form submitted successfully");}

else
{echo("Form not submitted");}}

else

{echo("All fields are required");}

?>

Note: PHP $_POST is a PHP super global variable which is used to collect form data after
submitting an HTML form with method="post".

mysqli_query(): This function accepts a string value representing a query as one of the
parameters and, executes/performs the given query on the database.

Syntax: mysqli_query($con, query)


con: This is an object representing a connection to MySQL Server.
Query: This is a string value representing the query to be executed.

//Another file which is a Html-form through which you will insert data into
the Database table

<html>

<body>

<form action="connection.php" method="post">

<label>Name</label> <input type="text" name="name"><br><br>

<label>Email</label> <input type="email" name="email"><br><br>

<label>Age</label> <input type="text" name="age"><br><br>

<label>Address</label> <input type="text" name="address"><br><br>

<button type="submit" name="submit"> Submit</button>

</form>

</body>

</html>
Error Handling: Error handling is the detection, and resolution of application,
programming or communication errors. Error handling helps in maintaining the
normal flow of program execution, as the errors in the program are deal
gracefully, thus making the program run well.

MySQLi: The error handling in MySQLi if a bit easier. The mysqli::$error


(mysqli_error) returns a string description of the last error.

<?php

if (!$mysqli->query("SET a=1")) {

printf("Errormessage: %s\n", $mysqli->error);

?>

Data Fetching:

MySQLi: MySQLi uses a loop for this purpose as well. The code, however, will
be a bit different.

<?php

while($row = $my_result->fetch_assoc()) {

echo $row['username'] . '\n';

?>
Database Insert Select Update and Delete, Issues in Writing Data to
Databases and generate reports:

//Insert.PHP – Insert Records Into MySQL DB

<?php

include_once 'connection1.php';

echo"<br>";

$name = 'Bhaskar';

$email = 'bh@gmail.com';

$age = '25';

$address = 'Banglore';

$sql = "INSERT INTO student (name,email,age, address)

VALUES ('$name', '$email', '$age', '$address' )";

if (mysqli_query($cn, $sql)) {

echo "New record has been added successfully !";

} else {

echo "Error: " . $sql . ":-" . mysqli_error($cn);

mysqli_close($cn);

?>

mysqli_error($cn):- This function returns the last error description for the most
recent function call, if any.
Syntax: mysqli_error(connection)

Here ‘connection’ is passed as a parameter which is required, it specifies the mysql


connection to use.

//Select.php – Select Record From MySQL DB

<?php

include_once 'connection.php';

$sql = "SELECT * FROM student";

$query = mysqli_query($cn,$sql);

if(!$query)

echo "Query does not work.".mysqli_error($cn);die;

while($data = mysqli_fetch_array($query))

echo "name = ".$data['name']."<br>";

echo "email = ".$data['email']."<br>";

echo "age = ".$data['age']."<br>";

echo "address = ".$data['address']."<br><hr>";

?>
//Update.php – Update Record Into MySQL DB

<?php

include_once 'connection.php';

echo"<br>";

$sql = "UPDATE student SET name = 'Raghav' WHERE


email='rr@gmail.com' ";

$query = mysqli_query($cn,$sql);

if(!$query)

echo "Query does not work.".mysqli_error($cn);die;

else

echo "Data successfully updated";

?>
//Delete.php – Delete Record From MySQL DB

<?php
include_once 'connection.php';

$sql = "DELETE FROM student WHERE email='rr@gmail.com'";

if (mysqli_query($cn, $sql)) {

echo "Record deleted successfully";

} else {

echo "Error deleting record: " . mysqli_error($cn);


}
mysqli_close($cn);
?>
--------------------------------------------------------------------------------------------

<?php
    include_once 'db.php';
 
    $sql = "DELETE FROM users WHERE userid='" . $_GET["userid"] . "'";
 
    if (mysqli_query($conn, $sql)) {
 
        echo "Record deleted successfully";
 
    } else {
     
        echo "Error deleting record: " . mysqli_error($conn);
    }
    mysqli_close($conn);
?>
Process user input:
<html>
<body>

<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>

</body>
</html>

When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php". The form data is
sent with the HTTP POST method.

To display the submitted data you could simply echo all the variables. The
"welcome.php" looks like this:

<html>
<body>

Welcome <?php echo $_POST["name"]; ?><br>


Your email address is: <?php echo $_POST["email"]; ?>

</body>
</html>
Object Oriented Programming with PHP and MySQL:

Procedural programming is about writing procedures or functions that perform


operations on the data, while object-oriented programming is about creating
objects that contain both data and functions.

Object-oriented programming has several advantages over procedural


programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes
the code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code
and shorter development time
PHP - What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented programming.

Look at the following illustration to see the difference between class and
objects:

Class: car
Objects: Volvo, Audi, Toyota

Class: Fruit
Objects: Apple, Mango, Grapes
So, a class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the properties and behaviors from the
class, but each object will have different values for the properties.

PHP OOP - Classes and Objects


OOP Case
Let's assume we have a class named Fruit. A Fruit can have properties like
name, color, weight, etc. We can define variables like $name, $color, and
$weight to hold the values of these properties.

When the individual objects (apple, banana, etc.) are created, they inherit all
the properties and behaviors from the class, but each object will have different
values for the properties.
Define a Class
A class is defined by using the class keyword, followed by the name of the class
and a pair of curly braces ({}). All its properties and methods go inside the
braces:

Syntax
<?php
class Fruit {
  // code goes here...
}
?>

Below we declare a class named Fruit consisting of two properties ($name and
$color) and two methods set_name() and get_name() for setting and getting
the $name property:

<?php
class Fruit {
  // Properties
  public $name;
  public $color;

  // Methods
  function set_name($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
}
?>

Define Objects
Classes are nothing without objects! We can create multiple objects from a
class. Each object has all the properties and methods defined in the class, but
they will have different property values.

Objects of a class is created using the new keyword.

In the example below, $apple and $banana are instances of the class Fruit:
<?php
class Fruit {
  // Properties
  public $name;
  public $color;

  // Methods
  function set_name($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
}

$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');

echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>

Example
<?php
class Fruit {
  // Properties
  public $name;
  public $color;

  // Methods
  function set_name($name) {
    $this->name = $name;
  }
  function get_name() {
    return $this->name;
  }
  function set_color($color) {
    $this->color = $color;
  }
  function get_color() {
    return $this->color;
  }
}

$apple = new Fruit();
$apple->set_name('Apple');
$apple->set_color('Red');
echo "Name: " . $apple->get_name();
echo "<br>";
echo "Color: " . $apple->get_color();
?>

PHP - The $this Keyword


The $this keyword refers to the current object, and is only available inside
methods.

<?php
class Fruit {
  public $name;
}
$apple = new Fruit();
?>

So, where can we change the value of the $name property? There are two
ways:

1. Inside the class (by adding a set_name() method and use $this):

<?php
class Fruit {
  public $name;
  function set_name($name) {
    $this->name = $name;
  }
}
$apple = new Fruit();
$apple->set_name("Apple");

echo $apple->name;
?>
2. Outside the class (by directly changing the property value):
<?php
class Fruit {
  public $name;
}
$apple = new Fruit();
$apple->name = "Apple";

echo $apple->name;
?>

PHP - instanceof
You can use the instanceof keyword to check if an object belongs to a specific class:

Example:

<?php
$apple = new Fruit();
var_dump($apple instanceof Fruit);
?>

You might also like