Contents-Database Connectivity – MySQL
Connecting to MySQL – Queries – Fetching Data Sets – Data About Data –
Multiple Connections – Creating MySQL Databases with PHP – MySQL
Functions – HTML Tables and Database Tables – Complex Mappings – Creating
the Sample Tables
Databases and MYSQL
Database
A database is a collection of data which is stored on a
computer
Why a database?
● Maintainability
● Scalability
● portability
MYSQL
● MySQL is the most popular database system used with PHP.
● 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
● 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.
Connecting to MySQL
● The basic command to initiate a MySQL connection is
mysql_connect($hostname, $user, $password);
Create database
The CREATE DATABASE statement is used to create a database in
MySQL.
Queries
● Create table
CREATE TABLE statement is used to create a table in MySQL.
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
● Insert data →INSERT INTO statement is used to add new records to a MySQL table
INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)
Queries
● Select data→ SELECT statement is used to select data from one or more tables
The SELECT statement is used to select data from one or more tables:
SELECT column_name(s) FROM table_name
Or Use the * character to select ALL columns from a table:
SELECT * FROM table_name
● Update data
UPDATE statement is used to update existing records in a table:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Queries
● Delete data
DELETE statement is used to delete records from a table:
DELETE FROM table_name WHERE some_column = some_value
Example (table creation)
<?php
$conn = mysqli_connect("localhost","root","","student");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE TABLE firstyears (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table Firstyear created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example (insert data)
<?php
$conn = mysqli_connect("localhost","root","","student");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO secondyear (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example (insert multipledata)
<?php
$conn = mysqli_connect("localhost","root","","student");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO secondyear (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO secondyear (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO secondyear (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example (update data)
<?php
$conn = mysqli_connect("localhost","root","","student");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE secondyear SET lastname='Ramu' WHERE firstname='Mary'";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example (delete data)
<?php
$conn = mysqli_connect("localhost","root","","student");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "DELETE FROM secondyear WHERE firstname='john' ";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Fetching Data Sets
Data can be fetched from MySql tables by executing SQL SELECT statement through
PHP function mysqli_query()
The fetching functions are as follows:
mysql_fetch_row: Returns row as an enumerated array
mysql_fetch_object: Returns row as an object
mysql_fetch_array: Returns row as an associative array
mysql_result: Returns one cell of data
mysql_fetch_assoc(): returns the row as an associative array
mysqli_data_seek(): it adjusts the result pointer to an arbitrary row in the result set
Example (mysql_fetch_row)
<?php
$conn = mysqli_connect("localhost","root","","student");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT firstname,lastname FROM thirdyear";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_row($result)) {
echo $row[0].$row[1]."<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Data About Data
● Metadata is “the data about the data.” Anything that describes the
database
● The MySQL metadata functions fall into two major categories:
○ Functions that return information about the previous operation only
○ Functions that return information about the database structure in
general
● mysqli_insert_id→ returns the auto incremented ID assigned to row of
data that inserted
● mysqli_field_count—> function returns the number of columns for the
most recent query.
Example (mysql_insert_id)
<?php
$conn = mysqli_connect("localhost","root","","student");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE TABLE thirddetai(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)";
$r=mysqli_query($conn, $sql);
$sql = "INSERT INTO thirddetai (firstname, lastname, email)
VALUES ('sudha', 'Doe', 'john@example.com')";
$result=mysqli_query($conn, $sql);
echo "id is".mysqli_insert_id($conn);
mysqli_close($conn);
?>
Example (mysql_field_count)
<?php
$conn = mysqli_connect("localhost","root","","student");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * from thirddetail";
$result = mysqli_query($conn,$sql);
$c= mysqli_field_count($conn);
echo $c;
mysqli_close($conn);
?>
Multiple Connections
● Multiple Mysql databases are connected into single web page
● It is useful to access data from multiple databases
Creating MySQL Databases with PHP
● To create a database from PHP, the user will need to have full
CREATE/DROP privileges on MySQL
● when you need to create databases programmatically, the relevant
functions are:
○ mysql_create_db(): Creates a database on the designated host, with name
specified in arguments
○ mysql_drop_db(): Deletes the specified database
○ mysql_query(): Passes table definitions and drops in this function
Example 1:(database creation and deletion)
<?php
$linkID = mysql_connect(‘localhost’, ‘root’, ‘sesame’);
mysql_create_db(‘new_db’, $linkID);
mysql_select_db(‘new_db’);
$query = “CREATE TABLE new_table (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
new_col VARCHAR(25))“;
$result = mysql_query($query);
$axe = mysql_drop_db(‘new_db’);
?>
HTML Tables and Database Tables
● A database table persistently stores information in columns,
which have predefined names and types so that the information in
them can be recovered later.
● An HTML table is a construct that tells the browser to lay out
arbitrary HTML contents in a rectangular array in the browser
window
One-to-one mapping
● HTML tables are really constructed out of rows (the <TR></TR> construct), and columns
have no independent existence — each row has some number of table datum items (the
<TD></TD>)
● Map database fields to HTML rows
● The simplest case of displaying a table is the one in which the structure of a database
table or query does correspond to the structure of the HTML table we want to display
● The database entity has m columns and n rows, and we’d like to display an m-by-n
rectangular grid in the user’s browser window, with all the cells filled in appropriately.
Example: A single-table displayer
● So let’s write a simple translator that queries the database for the contents of a single table
and displays the results on screen.
● Here’s the top-down outline of how the code will get the job done:
1. Establish a database connection.
2. Construct a query to send to the database.
3. Send the query and hold on to the result identifier that is returned.
4. Using the result identifier, find out how many columns (fields) there are in each row.
5. Start an HTML table.
6. Loop through the database result rows, printing a <TR></TR> pair to make a corresponding
HTML table row.
7. In each row, retrieve the successive fields and display them wrapped in a <TD></TD> pair.
8. Close off the HTML table.
9. Close the database connection.
Displaying column headers
● It’s conventional in HTML to use the <TH> element for column and/or row
headers — in most browsers and styles, this displays as a bold table cell.
● One improvement we can make is to optionally display column headers that
are based on the names of the table fields themselves.
● To actually retrieve those names, we can use the function
mysql_field_name().
Error checking
● die() →if they fail, an informative message will be printed
Example
<?php
$global_dbh = mysqli_connect("localhost", "root", "")or die("Could not connect to database");
mysqli_select_db($global_dbh,"student")or die("Could not select database");
function display_db_table($tablename, $connection)
{
$query_string = "SELECT * FROM $tablename";
$result_id = mysqli_query($connection,$query_string);
$column_count = mysqli_num_fields($result_id);
print("<TABLE BORDER=1>n");
print("<TR>");
for ($column_num = 0;$column_num < $column_count;$column_num++)
{
$field = mysqli_fetch_field_direct($result_id, $column_num);
print("<TH>");
print($field->name);
print ("</TH>");
}
print("</TR>n");
while ($row = mysqli_fetch_row($result_id))
{
print("<TR ALIGN=LEFT VALIGN=TOP>");
for($column_num=0;$column_num< column_count;$column_num++)
print("<TD>$row[$column_num]</TD>n");
print("</TR>n");
}print("</TABLE>n");
}?>
<HTML><HEAD><TITLE>student details</TITLE></HEAD>
<BODY><TABLE><TR><TD>
<?php
display_db_table("thirddetai", $global_dbh); ?>
</TD><TD>
<?php
display_db_table("thirdyear", $global_dbh); ?>
</TD></TR></TABLE></BODY></HTML>
Complex Mappings
● Every row in the resultset corresponds to a row in the table, and
the structure of the code is simply two nested loops.
● Unfortunately, life isn’t often this simple, and sometimes the
structure of the HTML table we want to display has a complex
relationship to the relational structure of the database tables.
● If we want to do a more complex mapping, we have a choice:
○ we can write more complex display code.
Example
<?php
$global_dbh = mysqli_connect("localhost", "root", "");
mysqli_select_db($global_dbh,"student");
function display_db_table($tablename, $connection)
{
$query_string = "SELECT firstname,lastname FROM $tablename ORDER BY firstname";
$result_id = mysqli_query($connection,$query_string);
$column_count = mysqli_num_fields($result_id);
print("<TABLE BORDER=1>n");
print("<TR><TH>firstname</TH><TH>lastname</TH></TR>");
while ($row = mysqli_fetch_row($result_id))
{
print("<TR ALIGN=LEFT VALIGN=TOP>");
for ($column_num = 0;$column_num < $column_count;$column_num++)
print("<TD>$row[$column_num]</TD>n");
print("</TR>n");
}
print("</TABLE>n");
<HTML>
<HEAD>
<TITLE>student details</TITLE>
</HEAD>
<BODY>
<TABLE><TR><TD>
<?php display_db_table("thirddetai", $global_dbh); ?>
</TD><TD>
<?php display_db_table("thirdyear", $global_dbh); ?>
</TD></TR></TABLE></BODY></HTML>
Example
<?php
$global_dbh = mysqli_connect("localhost", "root", "");
mysqli_select_db($global_dbh,"student");
function display_db_table($tablename, $connection)
{
$query_string = "SELECT firstname,lastname FROM $tablename where lastname='Doe' ORDER
BY firstname";
$result_id = mysqli_query($connection,$query_string);
$column_count = mysqli_num_fields($result_id);
print("<TABLE BORDER=1>n");
print("<TR><TH>firstname</TH><TH>lastname</TH></TR>");
while ($row = mysqli_fetch_row($result_id))
{
print("<TR ALIGN=LEFT VALIGN=TOP>");
for ($column_num = 0;$column_num < $column_count;$column_num++)
print("<TD>$row[$column_num]</TD>n");
print("</TR>n");
}
print("</TABLE>n");
<HTML>
<HEAD>
<TITLE>student details</TITLE>
</HEAD>
<BODY>
<TABLE><TR><TD>
<?php display_db_table("thirddetai", $global_dbh); ?>
</TD><TD>
<?php display_db_table("thirdyear", $global_dbh); ?>
</TD></TR></TABLE></BODY></HTML>