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

L 22 PHP and MySQL Connectivity

The document discusses database connectivity with PHP and MySQL. It covers topics like: 1. Using PhpMyAdmin to manage MySQL databases through a web interface with features like importing/exporting data, searching, and managing tables. 2. The basics of connecting to a MySQL database from PHP using mysqli_connect(), and how to open, close, and manipulate databases through queries. 3. Common SQL statements for databases like CREATE, INSERT, SELECT, and how to use them through PHP functions like mysqli_query() to create tables, insert data, and retrieve data.

Uploaded by

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

L 22 PHP and MySQL Connectivity

The document discusses database connectivity with PHP and MySQL. It covers topics like: 1. Using PhpMyAdmin to manage MySQL databases through a web interface with features like importing/exporting data, searching, and managing tables. 2. The basics of connecting to a MySQL database from PHP using mysqli_connect(), and how to open, close, and manipulate databases through queries. 3. Common SQL statements for databases like CREATE, INSERT, SELECT, and how to use them through PHP functions like mysqli_query() to create tables, insert data, and retrieve data.

Uploaded by

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

Database Systems

and Web
(15B11CI312)
Database Systems and Web

PHP and MySQL Connectivity


Topics Covered
Database Connectivity
MySQL & PHP
Database connectivity with PHP
To know database connectivity, one should know about PhpMyAdmin and MySQL readily available
with XAMPP.

PhpMyAdmin is one of the most popular applications for MySQL databases management. It is a free
tool written in PHP. Through this software you can create, alter, drop, delete, import and export
MySQL database tables. You can run MySQL queries, optimize, repair and check tables and ex
PhpMyAdmin Features
The main PhpMyAdmin features are as follows:

▪ User-friendly web interface

▪ Support for most MySQL functions like browse, drop, create, copy and alter databases, tables, views, fields and

indexes, execute MySQL queries, manage stored procedures and functions

▪ Import data from CSV and SQL files

▪ Export data to various formats: CSV, SQL, XML, PDF, ISO/IEC 26300 - OpenDocument Text and

Spreadsheet, Word, Excel, LATEX and others

▪ Searching globally in a database or a subset of it

▪ And much more.


PhpMyAdmin administration
PhpMyAdmin administration
In the upper part you will find the server hostname. The databases which you will manage are stored on
the same server as the software and the hostname is: localhost.

Under it there is information regarding the MySQL server, the MySQL client and the PhpMyAdmin
version.

Next, you will see the MySQL charset and you will be able to define the MySQL connection collation.

In the right column you can change the default language, alter the style, customize the theme color and
the font size. Also there you will notice links to PhpMyAdmin resources.
Databases area
In the Databases tab you will find a list with all the databases which can be managed through the localhost
server .

Once you click on a chosen database, you can start its management.
Status area
You can open the Status tab by clicking on the Show MySQL runtime information link. There you will find
detailed information regarding the MySQL server since the last restart.

You will see the traffic handled by the MySQL server, the maximum number of simultaneous connections,
the total number of connections, the failed and the aborted attempts, the total number of queries sent to the
server and more related details.
Status area
Variables area
The Variables tab will be opened after clicking on the Show MySQL system variables link.

You will see a list with the MySQL server system variables and their values.
Processes area
By clicking on the Processes link you will see all the processes running by your localhost server.
Export area
In the Export section you can export your database tables content in different formats (CSV, SQL, PDF,
Microsoft Excel, Microsoft Word, XML, and many more). You can select all the database tables or just
pick some of them.
Import area
In the Import section you can import your database tables from a file, saved on your local computer.

You should browse for the file and pick its character set from the drop-down menu.
MySQL
With PHP, you can connect to and manipulate databases.

MySQL is the most popular database system used with PHP.

PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform)

Databases are useful when storing information categorically. MySQL helps to store data in tables for a database.
For eg. A company may have a database with the following tables:

◦ Employees

◦ Products

◦ Customers

◦ Orders
PHP Connect to the MySQL Server

Three steps to connect to the MySql server :

• Open a Connection to the MySQL Server

• manipulation in MySql server

• Close a Connection
Open a Connection to the MySQL Server

mysqli_connect(host,username,password,dbname);
Before we can access data in a database, we must open a connection to the
MySQL server.

Parameter Description
host Optional. Either a host name or an IP address
username Optional. The MySQL user name
password Optional. The password to log in with
dbname Optional. The default database to be used when
performing queries
Open a Connection to the MySQL Server
<?php
// Create connection
$con=mysqli_connect(“localhost",“root","23","my_db");

// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Close a Connection
mysqli_close(connection_name)
The connection will be closed automatically when the script ends. To close
the connection before, use the mysqli_close() function.
Close a Connection
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");

// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_close($con);
?>
Create a Database
The CREATE DATABASE statement is used to create a database table in MySQL.

We must add the CREATE DATABASE statement to the mysqli_query() function to execute the
command.

The following example creates a database named "my_db":


<?php
$con=mysqli_connect("example.com","peter","abc123");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create database
$sql="CREATE DATABASE my_db";
if (mysqli_query($con,$sql))
{
echo "Database my_db created successfully";
}
else
{
echo "Error creating database: " . mysqli_error();
}
?>
Create a Table

The CREATE TABLE statement is used to create a table in MySQL.

We must add the CREATE TABLE statement to the mysqli_query() function to execute the command.

The following example creates a table named "Persons", with three columns. The column names will
be "Firstname", "Lastname" and "Age":
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Create table
$sql="CREATE TABLE persons(Firstname CHAR(30),Lastname CHAR(30),Age INT)”;
// Execute query
if (mysqli_query($con,$sql))
{
echo "Table persons created successfully"; }
else
{
echo "Error creating table: " . mysqli_error();
}
?>
Primary Keys and Auto Increment Fields

Each table in a database should have a primary key field.

A primary key is used to uniquely identify the rows in a table. Each primary key value must be unique
within the table. Furthermore, the primary key field cannot be null because the database engine requires
a value to locate the record.

The following example sets the PID field as the primary key field. The primary key field is often an ID
number, and is often used with the AUTO_INCREMENT setting. AUTO_INCREMENT automatically
increases the value of the field by 1 each time a new record is added. To ensure that the primary key
field cannot be null, we must add the NOT NULL setting to the field:
Primary Keys and Auto Increment Fields

$sql = "CREATE TABLE Persons


(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
Firstname CHAR(15),
Lastname CHAR(15),
Age INT
)";
Insert Data Into a Database Table

The INSERT INTO statement is used to add new records to a database table.

It is possible to write the INSERT INTO statement in two forms.


◦ The first form doesn't specify the column names where the data will be inserted, only their values:

INSERT INTO table_name VALUES (value1, value2, value3,...)


◦ The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin',35)");
mysqli_query($con,"INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Glenn', 'Quagmire',33)");
mysqli_close($con);
?>
Insert Data From a Form Into a Database

Now we will create an HTML form that can be used to add new records to the "Persons" table.

html>
<body>

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


Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>

</body>
</html>
Insert Data From a Form Into a Database

When a user clicks the submit button in the HTML form in the example above, the form data is sent to
"insert.php".

The "insert.php" file connects to a database, and retrieves the values from the form with the PHP
$_POST variables.

Then, the mysqli_query() function executes the INSERT INTO statement, and a new record will be
added to the "Persons" table.
Insert Data From a Form Into a Database
(INSERT.PHP)
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="INSERT INTO Persons (FirstName, LastName, Age)


VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error());
}
echo "1 record added";

mysqli_close($con);
?>
Select Data From a Database Table

SELECT column_name(s) FROM table_name

The SELECT statement is used to select data from a database.

$select_st = “select * from table_name ”;


Insert Data From a Form Into a Database
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM Persons");

while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}

mysqli_close($con);
?>
The WHERE clause

The SELECT statement is used to select data from a database.

SELECT column_name(s)
FROM table_name
WHERE column_name operator value
The WHERE clause
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons WHERE FirstName='Peter'");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
?>
Update Data In a Database

UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

The UPDATE statement is used to update existing records in a table.

Note: Notice the WHERE clause in the UPDATE syntax. The WHERE
clause specifies which record or records that should be updated. If you omit
the WHERE clause, all records will be updated!
<?php
Update Data In a Database
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE Persons SET Age=36
WHERE FirstName='Peter' AND LastName='Griffin'");

mysqli_close($con);
?>
Delete Data In a Database

DELETE FROM table_name


WHERE some_column = some_value

The DELETE FROM statement is used to delete records from a database


table.

Note: Notice the WHERE clause in the DELETE syntax. The WHERE
clause specifies which record or records that should be deleted. If you omit
the WHERE clause, all records will be deleted!
Delete Data In a Database

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"DELETE FROM Persons WHERE LastName='Griffin'");
mysqli_close($con);
?>
References
❖Tom Butler & Kevin Yank,”PHP and MySQL Novice to Ninja”, Sixth Edition, Site Point.

❖Lynn Beighley & Michael Morrison, “Head First PHP and MySQL”, First Edition, O’Reilly.

❖https://www.w3schools.com/php/DEFAULT.asp

❖https://www.tutorialspoint.com/php/index.htm

❖https://www.phpmyadmin.net

You might also like