L 22 PHP and MySQL Connectivity
L 22 PHP and MySQL Connectivity
and Web
(15B11CI312)
Database Systems and Web
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:
▪ Support for most MySQL functions like browse, drop, create, copy and alter databases, tables, views, fields and
▪ Export data to various formats: CSV, SQL, XML, PDF, ISO/IEC 26300 - OpenDocument Text and
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.
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
• 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.
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
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
The INSERT INTO statement is used to add new records to a database table.
Now we will create an HTML form that can be used to add new records to the "Persons" table.
html>
<body>
</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();
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error());
}
echo "1 record added";
mysqli_close($con);
?>
Select Data From a Database Table
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysqli_close($con);
?>
The WHERE clause
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
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
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