SlideShare une entreprise Scribd logo
1  sur  60
UNIT V
Database Connectivity – MySQL
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.
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, "");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE Faculty";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
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);
?>
Example (mysql_fetch_object)
<?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($obj=mysqli_fetch_object($result)) {
echo $obj->firstname.$obj->lastname. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Example (mysql_fetch_array)
<?php
$conn = mysqli_connect("localhost","root","","student");
// Check connection
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_array($result)) {
echo "Name " . $row["firstname"]. $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Example (mysql_fetch_assoc())
<?php
// Create connection
$conn = mysqli_connect("localhost","root","","student");
// Check connection
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) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Name " . $row["firstname"]. $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Example (mysql_data_seek())
<?php
// Create connection
$conn = mysqli_connect("localhost","root","","student");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * from thirdyear";
$result = mysqli_query($conn, $sql);
mysqli_data_seek($result,4);
$row=mysqli_fetch_row($result);
echo $row[1].$row[2].$row[0];
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
Example
<?php
$link1 = mysqli_connect("localhost", "root", "", "student");
$link2 = mysqli_connect("localhost", "root", "", "mydatabase");
if (!$link1) {
die("Connection failed: " . mysqli_connect_error());
}
if (!$link2) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT firstname, lastname FROM thirdyear";
$sql1 = "SELECT firstname, lastname FROM secondyear";
$result = mysqli_query($link1, $sql);
echo "thirdyear details";
while ($obj = mysqli_fetch_object($result)) {
echo $obj->firstname.$obj->lastname."<br>";
}
$result1 = mysqli_query($link2, $sql1);
echo "secondyear details";
while ($obj1 = mysqli_fetch_object($result1))
{
echo $obj1->firstname.$obj1-
>lastname."<br>";
}
mysqli_close($link1);
mysqli_close($link2);
?>
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’);
?>
Example 2:(database creation)
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, "");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE mydatabase1";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}mysqli_close($conn);?>
Example 3:(database deletion)
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, "");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = 'DROP DATABASE mydatabase2';
$retval = mysqli_query( $conn,$sql );
echo "database deleted";
mysqli_close($conn);
?>
MySQL data types
MySQL Functions
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.
Example
<?php
$global_dbh = mysqli_connect("localhost", "root", "");
mysqli_select_db($global_dbh,"student");
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");
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>
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>
Creating the Sample Tables
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, "mydatabase");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to create table
$sql = "CREATE TABLE fifthyear (
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
)";
mysqli_query($conn,$sql);
$sql = "INSERT INTO fifthyear (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO fifthyear (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO fifthyear (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')";
if (mysqli_multi_query($conn, $sql)) {
echo "table is created and New multiple records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<!DOCTYPE html>
<head>
<title>Store Data</title>
</head>
<body>
<center>
<h1>Storing Form data in Database</h1>
<form action="insert.php" method="post">
<label>First Name:</label>
<input type="text" name="firstname" id="firstName"><br>
<label>Last Name:</label>
<input type="text" name="lastname" id="lastName"><br>
<label>gender</label>
<input type="radio" name="gender" value='m'>Male
<input type="radio" name="gender" value='f'>Female<br>
<label>Address:</label>
<input type="text" name="address" id="Address"><br>
<label>Email Address:</label>
<input type="text" name="email" id="emailAddress"><br>
<label> country </label>
<select name="country">
<option value="india"> india </option>
<option value="UK"> UK </option>
<option value="US"> US</option>
</select><br>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>
<html> <body><center>
<?php
$conn = mysqli_connect("localhost","root","","mydatabase");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$firstname = $_REQUEST['firstname'];
$lastname = $_REQUEST['lastname'];
$gender = $_REQUEST['gender'];
$address = $_REQUEST['address'];
$email = $_REQUEST['email'];
$country = $_REQUEST['country'];
$sql = "INSERT INTO employee VALUES
('$firstname','$lastname','$gender','$address',
'$email','$country')";
if(mysqli_query($conn, $sql))
{
echo '<h3> The following data stored in a database
successfully </h3>';
echo("$firstname<br>$lastname<br>$gender<br>$ad
dress<br>$email<br>$country");
}
else{
echo "ERROR:". mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>
</center>
</body>
</html>
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College

Contenu connexe

Similaire à Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College

Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxModule 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
moirarandell
 
Ex[1].3 php db connectivity
Ex[1].3 php db connectivityEx[1].3 php db connectivity
Ex[1].3 php db connectivity
Mouli Chandira
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
okelloerick
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
salissal
 
Database presentation
Database presentationDatabase presentation
Database presentation
webhostingguy
 

Similaire à Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College (20)

Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxModule 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
 
Stored Procedure
Stored ProcedureStored Procedure
Stored Procedure
 
Php mysq
Php mysqPhp mysq
Php mysq
 
Ex[1].3 php db connectivity
Ex[1].3 php db connectivityEx[1].3 php db connectivity
Ex[1].3 php db connectivity
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
 
PHP and Mysql
PHP and MysqlPHP and Mysql
PHP and Mysql
 
Mysql & Php
Mysql & PhpMysql & Php
Mysql & Php
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Php summary
Php summaryPhp summary
Php summary
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for Newbies
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
 
Database presentation
Database presentationDatabase presentation
Database presentation
 
Synapse india reviews on php and sql
Synapse india reviews on php and sqlSynapse india reviews on php and sql
Synapse india reviews on php and sql
 
DBD::SQLite
DBD::SQLiteDBD::SQLite
DBD::SQLite
 
Php Mysql
Php Mysql Php Mysql
Php Mysql
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
veracruz
veracruzveracruz
veracruz
 
veracruz
veracruzveracruz
veracruz
 
veracruz
veracruzveracruz
veracruz
 
veracruz
veracruzveracruz
veracruz
 

Plus de Dhivyaa C.R

String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering CollegeString handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeBasics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Dhivyaa C.R
 
Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...
Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...
Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...
Dhivyaa C.R
 

Plus de Dhivyaa C.R (19)

Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
Regular expressions, Session and Cookies by Dr.C.R.Dhivyaa Kongu Engineering ...
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering CollegeString handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
String handling and arrays by Dr.C.R.Dhivyaa Kongu Engineering College
 
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeBasics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Basics of PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
Learning sets of Rules by Dr.C.R.Dhivyaa Kongu Engineering College
Learning sets of Rules by Dr.C.R.Dhivyaa Kongu Engineering CollegeLearning sets of Rules by Dr.C.R.Dhivyaa Kongu Engineering College
Learning sets of Rules by Dr.C.R.Dhivyaa Kongu Engineering College
 
Instance Learning and Genetic Algorithm by Dr.C.R.Dhivyaa Kongu Engineering C...
Instance Learning and Genetic Algorithm by Dr.C.R.Dhivyaa Kongu Engineering C...Instance Learning and Genetic Algorithm by Dr.C.R.Dhivyaa Kongu Engineering C...
Instance Learning and Genetic Algorithm by Dr.C.R.Dhivyaa Kongu Engineering C...
 
Artificial Neural Network by Dr.C.R.Dhivyaa Kongu Engineering College
Artificial Neural Network by Dr.C.R.Dhivyaa Kongu Engineering CollegeArtificial Neural Network by Dr.C.R.Dhivyaa Kongu Engineering College
Artificial Neural Network by Dr.C.R.Dhivyaa Kongu Engineering College
 
Bayesian Learning by Dr.C.R.Dhivyaa Kongu Engineering College
Bayesian Learning by Dr.C.R.Dhivyaa Kongu Engineering CollegeBayesian Learning by Dr.C.R.Dhivyaa Kongu Engineering College
Bayesian Learning by Dr.C.R.Dhivyaa Kongu Engineering College
 
Machine Learning Introduction by Dr.C.R.Dhivyaa Kongu Engineering College
Machine Learning Introduction by Dr.C.R.Dhivyaa Kongu Engineering CollegeMachine Learning Introduction by Dr.C.R.Dhivyaa Kongu Engineering College
Machine Learning Introduction by Dr.C.R.Dhivyaa Kongu Engineering College
 
Unit v -Construction and Evaluation
Unit v -Construction and EvaluationUnit v -Construction and Evaluation
Unit v -Construction and Evaluation
 
Unit iv -Documenting and Implementation of Software Architecture
Unit iv -Documenting and Implementation of Software ArchitectureUnit iv -Documenting and Implementation of Software Architecture
Unit iv -Documenting and Implementation of Software Architecture
 
Unit iii-Architecture in the lifecycle
Unit iii-Architecture in the lifecycleUnit iii-Architecture in the lifecycle
Unit iii-Architecture in the lifecycle
 
Unit v-Distributed Transaction and Replication
Unit v-Distributed Transaction and ReplicationUnit v-Distributed Transaction and Replication
Unit v-Distributed Transaction and Replication
 
Unit iv -Transactions
Unit iv -TransactionsUnit iv -Transactions
Unit iv -Transactions
 
Unit iii-Synchronization
Unit iii-SynchronizationUnit iii-Synchronization
Unit iii-Synchronization
 
Inter process communication by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engi...
Inter process communication by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engi...Inter process communication by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engi...
Inter process communication by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engi...
 
Quality attributes in software architecture by Dr.C.R.Dhivyaa, Assistant prof...
Quality attributes in software architecture by Dr.C.R.Dhivyaa, Assistant prof...Quality attributes in software architecture by Dr.C.R.Dhivyaa, Assistant prof...
Quality attributes in software architecture by Dr.C.R.Dhivyaa, Assistant prof...
 
Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...
Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...
Software architecture by Dr.C.R.Dhivyaa, Assistant Professor,Kongu Engineerin...
 
Distributed computing by Dr.C.R.Dhivyaa, Assistant Professor, Kongu Engineeri...
Distributed computing by Dr.C.R.Dhivyaa, Assistant Professor, Kongu Engineeri...Distributed computing by Dr.C.R.Dhivyaa, Assistant Professor, Kongu Engineeri...
Distributed computing by Dr.C.R.Dhivyaa, Assistant Professor, Kongu Engineeri...
 

Dernier

Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 

Dernier (20)

Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 

Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College

  • 2. 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
  • 3. Databases and MYSQL Database A database is a collection of data which is stored on a computer Why a database? ● Maintainability ● Scalability ● portability
  • 4. 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.
  • 5. 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.
  • 6. <?php $servername = "localhost"; $username = "root"; $password = ""; // Create connection $conn = mysqli_connect($servername, $username, ""); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Create database $sql = "CREATE DATABASE Faculty"; if (mysqli_query($conn, $sql)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysqli_error($conn); } mysqli_close($conn); ?>
  • 7. 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,...)
  • 8. 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
  • 9. Queries ● Delete data DELETE statement is used to delete records from a table: DELETE FROM table_name WHERE some_column = some_value
  • 10. 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); ?>
  • 11. 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); ?>
  • 12. 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); ?>
  • 13. 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); ?>
  • 14. 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); ?>
  • 15. 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
  • 16. 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); ?>
  • 17. Example (mysql_fetch_object) <?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($obj=mysqli_fetch_object($result)) { echo $obj->firstname.$obj->lastname. "<br>"; } } else { echo "0 results"; } mysqli_close($conn); ?>
  • 18. Example (mysql_fetch_array) <?php $conn = mysqli_connect("localhost","root","","student"); // Check connection 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_array($result)) { echo "Name " . $row["firstname"]. $row["lastname"]. "<br>"; } } else { echo "0 results"; } mysqli_close($conn); ?>
  • 19. Example (mysql_fetch_assoc()) <?php // Create connection $conn = mysqli_connect("localhost","root","","student"); // Check connection 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) { // output data of each row while($row = mysqli_fetch_assoc($result)) { echo "Name " . $row["firstname"]. $row["lastname"]. "<br>"; } } else { echo "0 results"; } mysqli_close($conn); ?>
  • 20. Example (mysql_data_seek()) <?php // Create connection $conn = mysqli_connect("localhost","root","","student"); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "SELECT * from thirdyear"; $result = mysqli_query($conn, $sql); mysqli_data_seek($result,4); $row=mysqli_fetch_row($result); echo $row[1].$row[2].$row[0]; mysqli_close($conn); ?>
  • 21. 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.
  • 22. 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); ?>
  • 23. 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); ?>
  • 24. Multiple Connections ● Multiple Mysql databases are connected into single web page ● It is useful to access data from multiple databases
  • 25. Example <?php $link1 = mysqli_connect("localhost", "root", "", "student"); $link2 = mysqli_connect("localhost", "root", "", "mydatabase"); if (!$link1) { die("Connection failed: " . mysqli_connect_error()); } if (!$link2) { die("Connection failed: " . mysqli_connect_error()); } $sql = "SELECT firstname, lastname FROM thirdyear"; $sql1 = "SELECT firstname, lastname FROM secondyear"; $result = mysqli_query($link1, $sql); echo "thirdyear details"; while ($obj = mysqli_fetch_object($result)) { echo $obj->firstname.$obj->lastname."<br>"; } $result1 = mysqli_query($link2, $sql1); echo "secondyear details"; while ($obj1 = mysqli_fetch_object($result1)) { echo $obj1->firstname.$obj1- >lastname."<br>"; } mysqli_close($link1); mysqli_close($link2); ?>
  • 26.
  • 27. 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
  • 28. 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’); ?>
  • 29. Example 2:(database creation) <?php $servername = "localhost"; $username = "root"; $password = ""; // Create connection $conn = mysqli_connect($servername, $username, ""); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Create database $sql = "CREATE DATABASE mydatabase1"; if (mysqli_query($conn, $sql)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysqli_error($conn); }mysqli_close($conn);?>
  • 30. Example 3:(database deletion) <?php $servername = "localhost"; $username = "root"; $password = ""; // Create connection $conn = mysqli_connect($servername, $username, ""); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = 'DROP DATABASE mydatabase2'; $retval = mysqli_query( $conn,$sql ); echo "database deleted"; mysqli_close($conn); ?>
  • 32.
  • 33.
  • 34.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40. 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
  • 41. 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.
  • 42. 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.
  • 43. Example <?php $global_dbh = mysqli_connect("localhost", "root", ""); mysqli_select_db($global_dbh,"student"); 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"); 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>
  • 44.
  • 45. 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
  • 46. 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>
  • 47.
  • 48. 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.
  • 49. 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>
  • 50.
  • 51. 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>
  • 52.
  • 53. Creating the Sample Tables <?php $servername = "localhost"; $username = "root"; $password = ""; // Create connection $conn = mysqli_connect($servername, $username, $password, "mydatabase"); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // sql to create table $sql = "CREATE TABLE fifthyear ( 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 )"; mysqli_query($conn,$sql);
  • 54. $sql = "INSERT INTO fifthyear (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com');"; $sql .= "INSERT INTO fifthyear (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com');"; $sql .= "INSERT INTO fifthyear (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"; if (mysqli_multi_query($conn, $sql)) { echo "table is created and New multiple records created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?>
  • 55.
  • 56. <!DOCTYPE html> <head> <title>Store Data</title> </head> <body> <center> <h1>Storing Form data in Database</h1> <form action="insert.php" method="post"> <label>First Name:</label> <input type="text" name="firstname" id="firstName"><br> <label>Last Name:</label> <input type="text" name="lastname" id="lastName"><br> <label>gender</label> <input type="radio" name="gender" value='m'>Male <input type="radio" name="gender" value='f'>Female<br> <label>Address:</label> <input type="text" name="address" id="Address"><br> <label>Email Address:</label> <input type="text" name="email" id="emailAddress"><br> <label> country </label> <select name="country"> <option value="india"> india </option> <option value="UK"> UK </option> <option value="US"> US</option> </select><br> <input type="submit" value="Submit"> </form> </center> </body> </html>
  • 57. <html> <body><center> <?php $conn = mysqli_connect("localhost","root","","mydatabase"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $firstname = $_REQUEST['firstname']; $lastname = $_REQUEST['lastname']; $gender = $_REQUEST['gender']; $address = $_REQUEST['address']; $email = $_REQUEST['email']; $country = $_REQUEST['country']; $sql = "INSERT INTO employee VALUES ('$firstname','$lastname','$gender','$address', '$email','$country')"; if(mysqli_query($conn, $sql)) { echo '<h3> The following data stored in a database successfully </h3>'; echo("$firstname<br>$lastname<br>$gender<br>$ad dress<br>$email<br>$country"); } else{ echo "ERROR:". mysqli_error($conn); } // Close connection mysqli_close($conn); ?> </center> </body> </html>