Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP DatabaseConnection

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 23

Study Session 3.

3
Using PHP-MyAdmin to work with MySQL database
This tutorial illustrates how to create a new database and a new user to access that database
on a MySQL Server using phpMyAdmin.
Introduction
phpMyAdmin is a popular web-based administration tool used to administrate MySQL servers
and databases.

1.0 PhpMyAdmin
phpMyAdmin is an open-source software tool introduced on September 9, 1998, which is written
in PHP. Basically, it is a third-party tool to manage the tables and data inside the database.

PhpMyAdmin supports various type of operations on MariaDB and MySQL. The main purpose
of phpMyAdmin is to handle the administration of MySQL over the web.

It is the most popular application for MySQL database management. We can create, update,
drop, alter, delete, import, and export MySQL database tables by using this software.
phpMyAdmin also supports a wide range of operation like managing databases, relations, tables,
columns, indexes, permissions, and users, etc., on MySQL and MariaDB. These operations can
be performed via user interface, while we still have the ability to execute any SQL statement.

phpMyAdmin is a GUI-based application which is used to manage MySQL database. We can


manually create database and table and execute the query on them. It provides a web-based
interface and can run on any server. Since it is web-based, so we can access it from any
computer.

1.1 Features of phpMyAdmin


phpMyAdmin supports several features that are given below:
i. phpMyAdmin can create, alter, browse, and drop databases, views, tables,
columns, and indexes.
ii. It can display multiple results sets through queries and stored procedures.
iii. phpMyAdmin use stored procedure and queries to display multiple results sets.
iv. It supports foreign keys
v. phpMyAdmin can track the changes done on databases, views, and tables.
vi. We can also create PDF graphics of our database layout.
vii. phpMyAdmin can be exported into various formats such as XML, CSV, PDF,
ISO/IEC 26300 - OpenDocument Text and Spreadsheet.
viii. It supports mysqli, which is the improved MySQL extension.
ix. phpMyAdmin can interact with 80 different languages.
x. phpMyAdmin can edit, execute, and bookmark any SQL-statements and even
batch-queries.
xi. By using a set of pre-defined functions, it can transform stored data into any
format. For example - BLOB-data as image or download-link.
xii. It provides the facility to backup the database into different forms.

1.2 Advantage of phpMyAdmin


phpMyAdmin can run on any server or any OS as it has a web browser. 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.
phpMyAdmin helps us to control the user's permission and operate several servers at the
same time.
 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.
 We can execute complex SQL statements and queries, create and edit functions,
triggers, and events using the graphical interface of phpMyAdmin.

1.3 Disadvantage of phpMyAdmin


 phpMyAdmin is a simple interface, but quite tough for a beginner to learn.
 phpMyAdmin is difficult to install as it needs three more software tools before
installation, which is- Apache server, PHP, and MySQL.
 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.
 It has no schema visualization.
 phpMyAdmin is a web-based software tool which runs only on the browser, so It
completely depends on browsers.
 It does not have auto-compilation capability.

Web server - phpMyAdmin's interface is based on our web browser, we need a web server to
keep phpMyAdmin's files inside it. Although we already have phpMyAdmin installed by default
as it is amongst the bundles that comes with the XAMPP server which we have already installed
in the beginning of this course.

You can use the links below for directives on how to install XAMPP SERVER:
 Video link: https://www.youtube.com/watch?v=-f8N4FEQWyY
 XAMPP download directives: https://www.javatpoint.com/phpMyAdmin
 XAMPP server download link: https://www.apachefriends.org/download.html
After the installation, test phpMyAdmin follow the steps below:
i. Launch XAMPP and start Apache and MySQL on the XAMPP control panel.
ii. Open up your browser
iii. Type in the url:  http://localhost/phpMyAdmin/
iv. The below site should be open if installation is correct and complete

1.4 phpMyAdmin MySQL

MySQL is the most popular database system used with PHP.

What is MySQL?
 MySQL is a database system used on the web
 MySQL is a database system that runs on a server
 MySQL is ideal for both small and large applications
 MySQL is very fast, reliable, and easy to use
 MySQL uses standard SQL
 MySQL compiles on a number of platforms
 MySQL is free to download and use
 MySQL is developed, distributed, and supported by Oracle Corporation
 MySQL is named after co-founder Monty Widenius's daughter: My
The data in a MySQL database are stored in tables.
A table is a collection of related data, and it consists of columns and rows. Databases are useful
for storing information categorically.
A company may have a database with the following tables:

 Employees
 Products
 Customers
 Orders
Study Session 3.4
Create and use connection using PHP Data Access Object (PDO) and MySQL

1.0 Manual database creation using phpMyAdmin’s graphical interface


Type: localhost/phpMyAdmin in the browser’s url and when it launches then Click on New (1)
to create a database and enter the database name in Create database (2) field and then click on
Create (3) button. We can create any number of databases.

Enter the table name, number of columns, and click on Go. A message will show that the
table is created successfully.
Now enter the field name, type, their size, and any constraint here and save it.

The table is created successfully. We can make changes in the table from here.
2.0 PHP Connection to MySQL
PHP 5 and later can work with a MySQL database using:

1. MySQLi extension (the "i" stands for improved)


2. PDO (PHP Data Objects)
Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in
2012.

MySQLi or PDO?
Both MySQLi and PDO have their advantages:

i. PDO will work on 12 different database systems, whereas MySQLi will only work with
MySQL databases. So, if you have to switch your project to use another database, PDO
makes the process easy. You only have to change the connection string and a few queries.
With MySQLi, you will need to rewrite the entire code - queries included.

ii. Both are object-oriented, but MySQLi also offers a procedural API.

iii. Both support Prepared Statements. Prepared Statements protect from SQL injection, and
are very important for web application security.

MySQL Examples in Both MySQLi and PDO Syntax


In this section we are going to demonstrate three ways of working with PHP and MySQL:

 MySQLi (object-oriented)
 MySQLi (procedural)
 PDO
Open a Connection to MySQL
Before we can access data in the MySQL database, we need to be able to connect to the server:
2.1 MySQL with PDO
PHP PDO is a database access layer that provides a uniform interface for working with multiple
databases.
PDO simplifies the common database operations including:
 Creating database connections
 Executing queries using prepared statements
 Calling stored procedures
 Performing transactions
 And handling errors
PDO allows you to work with any database that has a PDO driver available. PDO relies on
database-specific drivers, e.g., PDO_MYSQL for MySQL, PDO_PGSQL for PostgreSQL,
PDO_OCI for Oracle database, etc.
Therefore, to use PDO for a specific database, you need to have a corresponding database driver
available.

The following diagram illustrates how PDO works

PDO makes it easy to deploy PHP applications because it doesn’t require you to manually
include any script files in your application like other libraries.

2.1.1 Connecting to MySQL with PDO


Suppose you have a local MySQL database server that has the following information:
 The host is localhost.
 The bookdb database on the local database server.
 The account with the user: root
 password 'S@cr@t1!' that can access the bookdb database.
In PHP, you can create a config.php file and place the database parameters:

PDO Connection to MySQL

Note: In the PDO example above we have also specified a database (myDB). PDO require a
valid database to connect to. If no database is specified, an exception is thrown.

Tip: A great benefit of PDO is that it has an exception class to handle any problems that may
occur in our database queries. If an exception is thrown within the try{ } block, the script stops
executing and flows directly to the first catch(){ } block.

Closing the connection:

The statement below closes the MySQL connection


2.1.2 Creating database using PDO
The CREATE DATABASE statement is used to create a database in MySQL.
The following examples create a database named "myDB":

Closing the Object Oriented connection:

The statement below closes the MySQL connection


2.2 Database Connection Using MySQLi Procedural

Closing the Procedural connection:

The statement below closes the MySQL connection

2.1.2 Creating Database Using MySQLi Procedural:


2.3 MySQL with Object Oriented MySQLi

We can create the database and tables using phpMyAdmin graphical user interface as well as
with coding in php.

Making connection using MySQLi (Object Oriented)

Closing the connection:

The statement below closes the MySQL connection


2.3.1 Creating a database using MySQLi Object Oriented Approach:

PHP MySQL executing queries


After connecting to the database we need to run queries to fetch data. In Read
operations, we will use only select queries to fetch data from the database.
 PDO
$stmt = $conn->prepare($query);
$stmt->execute();
 MySQLi Procedural
mysqli_query($conn, $query)
 MySQLi Object-Oriented
$conn->query($query);

Close Connection: After the any operation is performed, it is a good practice to


always close the connection to the database using the close() function.

$conn->close();
2.4 How to Create Table in the database:

CREATE TABLE `Student Details` (

`Roll_No` int(11) NOT NULL,

`Name` varchar(255) NOT NULL,

`City` varchar(255) NOT NULL,

`Age` int(11) NOT NULL,

PRIMARY KEY (`Roll_No`)

);

3.0 Creating table using MySQLi Procedural Approach:


PHP mysql_query() function is used to create table. Since PHP 5.5, mysql_query() function is
deprecated. Now it is recommended to use one of the 2 alternatives.
 mysqli_query()
 PDO::__query()
Output

PHP MySQL Insert Record


PHP mysql_query() function is used to insert record in a table. It is recommended to use one of
the 2 alternatives.
 mysqli_query()
 PDO::__query()
Output:

Mysqli database table:

PHP MySQL Update Record


PHP mysql_query() function is used to update record in a table. It is recommended to use one of
the 2 alternatives.
 mysqli_query()
 PDO::__query()
Output:

PHP MySQL Delete Record


PHP mysql_query() function is used to delete record in a table. It is recommended to use one of
the 2 alternatives.
 mysqli_query()
 PDO::__query()
New database table data:

Here we will delete the 1st record from the emp5 database table using the mysqli delete query
Output

Database change effected

PHP MySQL Select Query


PHP mysql_query() function is used to execute select query. It is recommended to use one of the
2 alternatives.
 mysqli_query()
 PDO::__query()

There are two other MySQLi functions used in select query:


i. mysqli_num_rows(mysqli_result $result): returns number of rows.
ii. mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array. Each key
of the array represents the column name of the table. It return NULL if there are no more
rows.

Newly added rocord to the database table


Output:
MySQLi Object-Oriented approach for fetching data:

Output:
PDO approach for fetching data:
Output:

Summary and Conclusion


Php can make connection to the mysql database in various ways as we have seen in this section
of the course. It can also manipulate and populate the database using the insert, fetch, update and
delete database functions.

You might also like