SlideShare a Scribd company logo
Module 6:WEB SERVER AND SERVER SIDE SCRPTING,
PART-2
Chapter 19of Text Book
DATABSE Connection to MySQL / PHP
Internet & World Wide Web
How to Program, 5/e
YANBU UNIVERSITY COLLEGE
Management Science Department
© Yanbu University College
© Yanbu University College
DATABASE CONNECTIVITY
PHP combined with MySQL are cross-platform (you can
develop in Windows and serve on a Unix platform)
PHP Connect to the MySQL Server
Use the PHP mysqli_connect() function to open a new
connection to the MySQL server.
Open a Connection to the MySQL Server
Before we can access data in a database, we must open a
connection to the MySQL server.
In PHP, this is done with the mysqli_connect() function.
Syntax
mysqli_connect(host , username , password , dbname);
STEPS
CREATE A USER in PHPMyAdmin
CREATE A DATABASE
CONNECT TO DATABASE
DATA RETREIVAL/ MANIPULATION
© Yanbu University College
© Yanbu University College
© Yanbu University College
© Yanbu University College
© Yanbu University College
PHP Create Database and Tables
A database holds one or more tables.
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 “MIS352":
<?php
$con=mysqli_connect(“localhost",“haseena",“husna");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " .
mysqli_connect_error();
}
// Create database
$sql="CREATE DATABASE MIS352";
if (mysqli_query($con,$sql))
{
echo "Database MIS352 created successfully";
}
else
{
echo "Error creating database: " . mysqli_error();
}
?>
© Yanbu University College
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 “MArks", with
three columns. The column names will be “STD_ID",
“STD_NAME" and “STD_MARKS":
<?php
$con=mysqli_connect("localhost","PHPClass","hello","MIS352"
);
// Check connection
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL:" . mysqli_connect_error();
}
// Create table
$sql="CREATE TABLE Marks(STD_ID
CHAR(30),STD_NAME CHAR(30),STD_MARKS INTO(20))";
// Execute query
if(mysqli_query($con,$sql))
{echo "Table Marks created successfully";}
else
{ echo "Error in creating table: " . mysqli_error();
}
?>
Note: When you create a database field of type CHAR, you must
specify the maximum length of the field, e.g. CHAR(50).
The data type specifies what type of data the column can hold.
© Yanbu University College
PHP MySQL Insert Into
Insert Data Into a Database Table
The INSERT INTO statement is used to add new records to a
database table.
Syntax
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,...)
© Yanbu University College
PHP MySQL Insert Into
Example:In the previous slide we created a table named
“Marks", with three columns; “STD_ID", “STD_Name" and
“STD_Marks". We will use the same table in this example. The
following example adds two new records to the “Marks" table:
<?php
// connect with the database and user in Php Myadmin
$n=mysqli_connect("localhost","PHPClass","hello","MIS352");
if (mysqli_connect_errno())
{
echo(" Error In connection");
}
else
{ echo("database connected");
}
$stuid=($_POST['sid']);
$stuname=($_POST['sn']);
$stumarks=intval($_POST['sa']);
$sql="insert into Marks(STD_ID,STD_NAME,STD_MARKS)
values
('$stuid','$stuname',$stumarks)";
if(mysqli_query($n,$sql))
{echo "<center><h1 style='color:aqua'>Record added
successfully";}
else
{echo"error in insertion";}
mysqli_close($n);
?>
© Yanbu University College
Insert Data From a Form Into a Database
HTML FILE
<html>
<body>
<h1> Insert your Detail in the DATABSE </h1>
<FORM ACTION="new_insert.php" method="post" name="f1">
<label>ID &nbsp; &nbsp;<input type="text"
name="sid"></label><br> <br>
<label>NAME&nbsp; &nbsp;<input type="text"
name="sn"></label><br> <br>
<label>MARKS&nbsp; &nbsp;<input type="text"
name="sa"></label><br> <br>
<label><br><br>
<input type="submit" name="b1" Value="INSERT">
<input type="reset" >
</form>
</body>
</html>
OUT PUT
Now we will create an HTML form that can be used to add new
records to the “MIS352" table. Here is the HTML form:
© Yanbu University College
11
Insert Data From a Form Into a Database
Inserting record
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 “Marks" table.
Here is the "insert.php" page:
© Yanbu University College
Insert Data From a Form Into a Database(contd)
Insert.php
<?php
// connect with the database and user in Php Myadmin
$n=mysqli_connect("localhost","PHPClass","hello","MIS352");
if (mysqli_connect_errno())
{ echo(" Error In connection"); }
else
{ echo("database connected"); }
$stuid=($_POST['sid']);
$stuname=($_POST['sn']);
$stumarks=intval($_POST['sa']);
$sql="insert into Marks(STD_ID,STD_NAME,STD_MARKS)
values
('$stuid','$stuname',$stumarks)";
if(mysqli_query($n,$sql))
{echo "<center><h1 style='color:aqua'>Record added
successfully";}
else
{echo"error in insertion";}
mysqli_close($n);
?>
OUTPUT:
© Yanbu University College
PHP MySQL Select
Select Data From a Database Table
The SELECT statement is used to select data from a database.
Syntax
SELECT column_name(s) FROM table_name
To get PHP to execute the statement above we must use the
mysqli_query() function. This function is used to send a query
or command to a MySQL connection.
The example below stores the data returned by the
mysql_query() function in the $result variable.
Next, we use the mysqli_fetch_array() function to return the
first row from the recordset as an array.
Each call to mysqli_fetch_array() returns the next row in the
recordset.
The while loop loops through all the records in the recordset.
To print the value of each row, we use the PHP $row variable
($row['FirstName'] and $row['LastName']).
© Yanbu University College
<?php
echo "<h1 style='color:magenta'>The contents of Marks
Table:</h1><br> <br>";
$con=mysqli_connect("localhost","PHPClass","hello","MIS352"
);
// Check connection
if (mysqli_connect_errno())
{ echo "Failed to connect to MySQL: " .
mysqli_connect_error(); }
$result = mysqli_query($con,"SELECT * FROM Marks");
echo "<center> <table border='1'><tr>
<th>STD_ID</th>
<th>STD_NAME</th>
<th>STD_MARKS</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['STD_ID'] . "</td>";
echo "<td>" . $row['STD_NAME'] . "</td>";
echo "<td>" . $row['STD_MARKS'] . "</td>";
echo "</tr>";
}
echo "</center></table>";
mysqli_close($con);
?>
DATABASE CONNECTIVITY Complete example WITH
mysqli_connect()
© Yanbu University College
<html><Head></head>
<body><p> ID NAME EMAIL </p><br>
<?php
//connection to the database
$con=mysqli_connect("localhost",”haseena",”husna","mis352");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " .
mysqli_connect_error();
}
//execute the SQL query and return records
$result = mysqli_query($con,"SELECT * FROM student");
//fetch tha data from the database
while($row = mysqli_fetch_array($result))
{
//display the results
echo $row['ID'] . " " . $row['NAME']. " "
. $row['EMAIL'];
echo "<br />";
}
//close the connection
mysqli_close($con);
?> </body></html>
DATABASE CONNECTIVITY Complete example WITH
mysqli_connect()
© Yanbu University College
Output
© Yanbu University College
Die() Function
Definition and Usage
The die() function prints a message and exits the current script.
This function is an alias of the exit() function.
E.g.
//connection to the database
$dbhandle = mysql_connect(‘hostname’, ‘username’,
‘password’)
or die("Unable to connect to MySQL");
© Yanbu University College
DATABASE CONNECTIVITY WITH mysql_connect()
<?php
//connection to the database
$dbhandle = mysql_connect(‘hostname’, ‘username’,
‘password’)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT id, model,year FROM cars");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'model'}."Year:
". //display the results
$row{'year'}."<br>";
}
//close the connection
mysql_close($dbhandle);
?>
© Yanbu University College
PHP MySQL The Where Clause
<?php
$con=mysqli_connect("localhost",”PHPClass",”hello","mis352"
);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM student
WHERE NAME='hia' ");
while($row = mysqli_fetch_array($result))
{
echo $row['ID'] . " " . $row['NAME'] . " " . $row['EMAIL'];
echo "<br>";
}
?>
© Yanbu University College
PHP MySQL Order By Keyword
The ORDER BY Keyword
The ORDER BY keyword is used to sort the data in a recordset
in ascending order by default.
If you want to sort the records in a descending order, you can
use the DESC keyword
<?php
$con=mysqli_connect("localhost",”PHPClass",”Hello","mis352"
);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM student
ORDER BY ID ");
while($row = mysqli_fetch_array($result))
{
echo $row['ID'] . " " . $row['NAME'] . " " . $row['EMAIL'];
echo "<br>";
}
?>
© Yanbu University College
PHP MySQL Update
The UPDATE statement is used to modify data in a table.
<?php
$con=mysqli_connect("localhost",”PHPClass",”Hello","mis352"
);
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$b ="UPDATE student SET ID=36 WHERE NAME=‘Hasi' AND
EMAIL=‘[email protected]'";
if (mysqli_query($con,$b))
{
echo("RECORD UPDATED SUCCESFUL ");
}
?>
© Yanbu University College
PHP MySQL Delete
The DELETE FROM statement is used to delete records from a
database table.
<?php
$con=mysqli_connect("localhost","PHPClass","hello","MIS352"
);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$a="DELETE FROM Marks WHERE STD_NAME='Malak'";
if (mysqli_query($con,$a))
{
echo "1 record Deleted";
}
else
{
echo "Error in Deletion the record: " . mysqli_error();
}
mysqli_close($con);
?>
OUTPUT:
© Yanbu University College

More Related Content

Similar to Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx

Php mysql connectivity
Php mysql connectivityPhp mysql connectivity
Php mysql connectivity
abhikwb
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
wahidullah mudaser
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
Stored Procedure
Stored ProcedureStored Procedure
Stored Procedure
NidiaRamirez07
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
okelloerick
 
How to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdfHow to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdf
Appweb Coders
 
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
FYBSC IT Web Programming Unit V  Advanced PHP and MySQLFYBSC IT Web Programming Unit V  Advanced PHP and MySQL
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
Arti Parab Academics
 
Ex[1].3 php db connectivity
Ex[1].3 php db connectivityEx[1].3 php db connectivity
Ex[1].3 php db connectivityMouli Chandira
 
Python my sql database connection
Python my sql   database connectionPython my sql   database connection
Python my sql database connection
Learnbay Datascience
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actionsAren Zomorodian
 
Excel to SQL Server
Excel to SQL ServerExcel to SQL Server
Excel to SQL Serverchat000
 
Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For Beginners
Priti Solanki
 
Php mysq
Php mysqPhp mysq
Php mysq
prasanna pabba
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxPHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptx
CynthiaKendi1
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sqlsalissal
 

Similar to Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx (20)

Php mysql connectivity
Php mysql connectivityPhp mysql connectivity
Php mysql connectivity
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
Sql
SqlSql
Sql
 
Stored Procedure
Stored ProcedureStored Procedure
Stored Procedure
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
 
How to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdfHow to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdf
 
Php 2
Php 2Php 2
Php 2
 
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
FYBSC IT Web Programming Unit V  Advanced PHP and MySQLFYBSC IT Web Programming Unit V  Advanced PHP and MySQL
FYBSC IT Web Programming Unit V Advanced PHP and MySQL
 
Ex[1].3 php db connectivity
Ex[1].3 php db connectivityEx[1].3 php db connectivity
Ex[1].3 php db connectivity
 
Python my sql database connection
Python my sql   database connectionPython my sql   database connection
Python my sql database connection
 
Web Technologies - forms and actions
Web Technologies -  forms and actionsWeb Technologies -  forms and actions
Web Technologies - forms and actions
 
PHP with MYSQL
PHP with MYSQLPHP with MYSQL
PHP with MYSQL
 
Php summary
Php summaryPhp summary
Php summary
 
Excel to SQL Server
Excel to SQL ServerExcel to SQL Server
Excel to SQL Server
 
Php MySql For Beginners
Php MySql For BeginnersPhp MySql For Beginners
Php MySql For Beginners
 
Php mysq
Php mysqPhp mysq
Php mysq
 
MAD UNIT 5 FINAL.pptx
MAD UNIT 5 FINAL.pptxMAD UNIT 5 FINAL.pptx
MAD UNIT 5 FINAL.pptx
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxPHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptx
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
 

More from moirarandell

BOOK REVIEWS How to write a book review There are two .docx
BOOK REVIEWS How to write a book review  There are two .docxBOOK REVIEWS How to write a book review  There are two .docx
BOOK REVIEWS How to write a book review There are two .docx
moirarandell
 
Book Review #3- The Spirit Catches You and You Fall Down”Ch.docx
Book Review #3- The Spirit Catches You and You Fall Down”Ch.docxBook Review #3- The Spirit Catches You and You Fall Down”Ch.docx
Book Review #3- The Spirit Catches You and You Fall Down”Ch.docx
moirarandell
 
Book required Current Issues and Enduring Questions, by Sylvan Ba.docx
Book required Current Issues and Enduring Questions, by Sylvan Ba.docxBook required Current Issues and Enduring Questions, by Sylvan Ba.docx
Book required Current Issues and Enduring Questions, by Sylvan Ba.docx
moirarandell
 
Book Review #1- The Spirit Catches You and You Fall Down”Chapte.docx
Book Review #1- The Spirit Catches You and You Fall Down”Chapte.docxBook Review #1- The Spirit Catches You and You Fall Down”Chapte.docx
Book Review #1- The Spirit Catches You and You Fall Down”Chapte.docx
moirarandell
 
Book reportGringo viejo- Carlos FuentesThe written book repo.docx
Book reportGringo viejo- Carlos FuentesThe written book repo.docxBook reportGringo viejo- Carlos FuentesThe written book repo.docx
Book reportGringo viejo- Carlos FuentesThe written book repo.docx
moirarandell
 
Book reference Kouzes, James M. and Posner, Barry Z. The Leadership.docx
Book reference Kouzes, James M. and Posner, Barry Z. The Leadership.docxBook reference Kouzes, James M. and Posner, Barry Z. The Leadership.docx
Book reference Kouzes, James M. and Posner, Barry Z. The Leadership.docx
moirarandell
 
BOOK PICTURE I POSTED TOO. Go to the the textbook, study chapt.docx
BOOK PICTURE I POSTED TOO. Go to the the textbook, study chapt.docxBOOK PICTURE I POSTED TOO. Go to the the textbook, study chapt.docx
BOOK PICTURE I POSTED TOO. Go to the the textbook, study chapt.docx
moirarandell
 
Book ListBecker, Ernest The Denial of D.docx
Book ListBecker, Ernest                          The Denial of D.docxBook ListBecker, Ernest                          The Denial of D.docx
Book ListBecker, Ernest The Denial of D.docx
moirarandell
 
Book list below.docx
Book list below.docxBook list below.docx
Book list below.docx
moirarandell
 
Book is Media Literacy. Eighth EditionW.JamesPotte.docx
Book is Media Literacy. Eighth EditionW.JamesPotte.docxBook is Media Literacy. Eighth EditionW.JamesPotte.docx
Book is Media Literacy. Eighth EditionW.JamesPotte.docx
moirarandell
 
Book Forensic and Investigative AccountingPlease answer t.docx
Book Forensic and Investigative AccountingPlease answer t.docxBook Forensic and Investigative AccountingPlease answer t.docx
Book Forensic and Investigative AccountingPlease answer t.docx
moirarandell
 
Book Criminoloy Second EditionRead Chapter 6. Please submit .docx
Book Criminoloy Second EditionRead Chapter 6. Please submit .docxBook Criminoloy Second EditionRead Chapter 6. Please submit .docx
Book Criminoloy Second EditionRead Chapter 6. Please submit .docx
moirarandell
 
Book Discussion #2 Ideas(may select 1 or more to respond to).docx
Book Discussion #2 Ideas(may select 1 or more to respond to).docxBook Discussion #2 Ideas(may select 1 or more to respond to).docx
Book Discussion #2 Ideas(may select 1 or more to respond to).docx
moirarandell
 
BOOK 1984 MiniProject What makes a human beingOne .docx
BOOK 1984 MiniProject What makes a human beingOne .docxBOOK 1984 MiniProject What makes a human beingOne .docx
BOOK 1984 MiniProject What makes a human beingOne .docx
moirarandell
 
Bonnie Morgen First Day on the Job and Facing an Ethical Di.docx
Bonnie Morgen First Day on the Job and Facing an Ethical Di.docxBonnie Morgen First Day on the Job and Facing an Ethical Di.docx
Bonnie Morgen First Day on the Job and Facing an Ethical Di.docx
moirarandell
 
Bonds are a vital source of financing to governments and corpora.docx
Bonds are a vital source of financing to governments and corpora.docxBonds are a vital source of financing to governments and corpora.docx
Bonds are a vital source of financing to governments and corpora.docx
moirarandell
 
Bond Company adopted the dollar-value LIFO inventory method on Janua.docx
Bond Company adopted the dollar-value LIFO inventory method on Janua.docxBond Company adopted the dollar-value LIFO inventory method on Janua.docx
Bond Company adopted the dollar-value LIFO inventory method on Janua.docx
moirarandell
 
Boley A Negro Town in the American West (1908) The commu.docx
Boley A Negro Town in the American West (1908)  The commu.docxBoley A Negro Town in the American West (1908)  The commu.docx
Boley A Negro Town in the American West (1908) The commu.docx
moirarandell
 
Bolsonaro and Brazils Illiberal Backlash Wendy Hunter, Timo.docx
Bolsonaro and Brazils Illiberal Backlash Wendy Hunter, Timo.docxBolsonaro and Brazils Illiberal Backlash Wendy Hunter, Timo.docx
Bolsonaro and Brazils Illiberal Backlash Wendy Hunter, Timo.docx
moirarandell
 
BoF Professional Member Exclusive articles & analysis availa.docx
BoF Professional  Member Exclusive articles & analysis availa.docxBoF Professional  Member Exclusive articles & analysis availa.docx
BoF Professional Member Exclusive articles & analysis availa.docx
moirarandell
 

More from moirarandell (20)

BOOK REVIEWS How to write a book review There are two .docx
BOOK REVIEWS How to write a book review  There are two .docxBOOK REVIEWS How to write a book review  There are two .docx
BOOK REVIEWS How to write a book review There are two .docx
 
Book Review #3- The Spirit Catches You and You Fall Down”Ch.docx
Book Review #3- The Spirit Catches You and You Fall Down”Ch.docxBook Review #3- The Spirit Catches You and You Fall Down”Ch.docx
Book Review #3- The Spirit Catches You and You Fall Down”Ch.docx
 
Book required Current Issues and Enduring Questions, by Sylvan Ba.docx
Book required Current Issues and Enduring Questions, by Sylvan Ba.docxBook required Current Issues and Enduring Questions, by Sylvan Ba.docx
Book required Current Issues and Enduring Questions, by Sylvan Ba.docx
 
Book Review #1- The Spirit Catches You and You Fall Down”Chapte.docx
Book Review #1- The Spirit Catches You and You Fall Down”Chapte.docxBook Review #1- The Spirit Catches You and You Fall Down”Chapte.docx
Book Review #1- The Spirit Catches You and You Fall Down”Chapte.docx
 
Book reportGringo viejo- Carlos FuentesThe written book repo.docx
Book reportGringo viejo- Carlos FuentesThe written book repo.docxBook reportGringo viejo- Carlos FuentesThe written book repo.docx
Book reportGringo viejo- Carlos FuentesThe written book repo.docx
 
Book reference Kouzes, James M. and Posner, Barry Z. The Leadership.docx
Book reference Kouzes, James M. and Posner, Barry Z. The Leadership.docxBook reference Kouzes, James M. and Posner, Barry Z. The Leadership.docx
Book reference Kouzes, James M. and Posner, Barry Z. The Leadership.docx
 
BOOK PICTURE I POSTED TOO. Go to the the textbook, study chapt.docx
BOOK PICTURE I POSTED TOO. Go to the the textbook, study chapt.docxBOOK PICTURE I POSTED TOO. Go to the the textbook, study chapt.docx
BOOK PICTURE I POSTED TOO. Go to the the textbook, study chapt.docx
 
Book ListBecker, Ernest The Denial of D.docx
Book ListBecker, Ernest                          The Denial of D.docxBook ListBecker, Ernest                          The Denial of D.docx
Book ListBecker, Ernest The Denial of D.docx
 
Book list below.docx
Book list below.docxBook list below.docx
Book list below.docx
 
Book is Media Literacy. Eighth EditionW.JamesPotte.docx
Book is Media Literacy. Eighth EditionW.JamesPotte.docxBook is Media Literacy. Eighth EditionW.JamesPotte.docx
Book is Media Literacy. Eighth EditionW.JamesPotte.docx
 
Book Forensic and Investigative AccountingPlease answer t.docx
Book Forensic and Investigative AccountingPlease answer t.docxBook Forensic and Investigative AccountingPlease answer t.docx
Book Forensic and Investigative AccountingPlease answer t.docx
 
Book Criminoloy Second EditionRead Chapter 6. Please submit .docx
Book Criminoloy Second EditionRead Chapter 6. Please submit .docxBook Criminoloy Second EditionRead Chapter 6. Please submit .docx
Book Criminoloy Second EditionRead Chapter 6. Please submit .docx
 
Book Discussion #2 Ideas(may select 1 or more to respond to).docx
Book Discussion #2 Ideas(may select 1 or more to respond to).docxBook Discussion #2 Ideas(may select 1 or more to respond to).docx
Book Discussion #2 Ideas(may select 1 or more to respond to).docx
 
BOOK 1984 MiniProject What makes a human beingOne .docx
BOOK 1984 MiniProject What makes a human beingOne .docxBOOK 1984 MiniProject What makes a human beingOne .docx
BOOK 1984 MiniProject What makes a human beingOne .docx
 
Bonnie Morgen First Day on the Job and Facing an Ethical Di.docx
Bonnie Morgen First Day on the Job and Facing an Ethical Di.docxBonnie Morgen First Day on the Job and Facing an Ethical Di.docx
Bonnie Morgen First Day on the Job and Facing an Ethical Di.docx
 
Bonds are a vital source of financing to governments and corpora.docx
Bonds are a vital source of financing to governments and corpora.docxBonds are a vital source of financing to governments and corpora.docx
Bonds are a vital source of financing to governments and corpora.docx
 
Bond Company adopted the dollar-value LIFO inventory method on Janua.docx
Bond Company adopted the dollar-value LIFO inventory method on Janua.docxBond Company adopted the dollar-value LIFO inventory method on Janua.docx
Bond Company adopted the dollar-value LIFO inventory method on Janua.docx
 
Boley A Negro Town in the American West (1908) The commu.docx
Boley A Negro Town in the American West (1908)  The commu.docxBoley A Negro Town in the American West (1908)  The commu.docx
Boley A Negro Town in the American West (1908) The commu.docx
 
Bolsonaro and Brazils Illiberal Backlash Wendy Hunter, Timo.docx
Bolsonaro and Brazils Illiberal Backlash Wendy Hunter, Timo.docxBolsonaro and Brazils Illiberal Backlash Wendy Hunter, Timo.docx
Bolsonaro and Brazils Illiberal Backlash Wendy Hunter, Timo.docx
 
BoF Professional Member Exclusive articles & analysis availa.docx
BoF Professional  Member Exclusive articles & analysis availa.docxBoF Professional  Member Exclusive articles & analysis availa.docx
BoF Professional Member Exclusive articles & analysis availa.docx
 

Recently uploaded

Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
Col Mukteshwar Prasad
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 

Recently uploaded (20)

Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
How to Break the cycle of negative Thoughts
How to Break the cycle of negative ThoughtsHow to Break the cycle of negative Thoughts
How to Break the cycle of negative Thoughts
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 

Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx

  • 1. Module 6:WEB SERVER AND SERVER SIDE SCRPTING, PART-2 Chapter 19of Text Book DATABSE Connection to MySQL / PHP Internet & World Wide Web How to Program, 5/e YANBU UNIVERSITY COLLEGE Management Science Department © Yanbu University College © Yanbu University College DATABASE CONNECTIVITY PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform) PHP Connect to the MySQL Server Use the PHP mysqli_connect() function to open a new connection to the MySQL server. Open a Connection to the MySQL Server Before we can access data in a database, we must open a connection to the MySQL server. In PHP, this is done with the mysqli_connect() function. Syntax mysqli_connect(host , username , password , dbname); STEPS CREATE A USER in PHPMyAdmin CREATE A DATABASE
  • 2. CONNECT TO DATABASE DATA RETREIVAL/ MANIPULATION © Yanbu University College © Yanbu University College © Yanbu University College © Yanbu University College
  • 3. © Yanbu University College PHP Create Database and Tables A database holds one or more tables. 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 “MIS352": <?php $con=mysqli_connect(“localhost",“haseena",“husna"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } // Create database $sql="CREATE DATABASE MIS352"; if (mysqli_query($con,$sql)) { echo "Database MIS352 created successfully"; } else { echo "Error creating database: " . mysqli_error(); } ?>
  • 4. © Yanbu University College 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 “MArks", with three columns. The column names will be “STD_ID", “STD_NAME" and “STD_MARKS": <?php $con=mysqli_connect("localhost","PHPClass","hello","MIS352" ); // Check connection if(mysqli_connect_errno()) { echo "Failed to connect to MySQL:" . mysqli_connect_error(); } // Create table $sql="CREATE TABLE Marks(STD_ID CHAR(30),STD_NAME CHAR(30),STD_MARKS INTO(20))"; // Execute query if(mysqli_query($con,$sql)) {echo "Table Marks created successfully";} else { echo "Error in creating table: " . mysqli_error(); } ?> Note: When you create a database field of type CHAR, you must specify the maximum length of the field, e.g. CHAR(50). The data type specifies what type of data the column can hold.
  • 5. © Yanbu University College PHP MySQL Insert Into Insert Data Into a Database Table The INSERT INTO statement is used to add new records to a database table. Syntax 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,...) © Yanbu University College PHP MySQL Insert Into Example:In the previous slide we created a table named “Marks", with three columns; “STD_ID", “STD_Name" and “STD_Marks". We will use the same table in this example. The following example adds two new records to the “Marks" table: <?php // connect with the database and user in Php Myadmin $n=mysqli_connect("localhost","PHPClass","hello","MIS352"); if (mysqli_connect_errno())
  • 6. { echo(" Error In connection"); } else { echo("database connected"); } $stuid=($_POST['sid']); $stuname=($_POST['sn']); $stumarks=intval($_POST['sa']); $sql="insert into Marks(STD_ID,STD_NAME,STD_MARKS) values ('$stuid','$stuname',$stumarks)"; if(mysqli_query($n,$sql)) {echo "<center><h1 style='color:aqua'>Record added successfully";} else {echo"error in insertion";} mysqli_close($n); ?> © Yanbu University College Insert Data From a Form Into a Database HTML FILE <html> <body> <h1> Insert your Detail in the DATABSE </h1> <FORM ACTION="new_insert.php" method="post" name="f1"> <label>ID &nbsp; &nbsp;<input type="text" name="sid"></label><br> <br> <label>NAME&nbsp; &nbsp;<input type="text" name="sn"></label><br> <br> <label>MARKS&nbsp; &nbsp;<input type="text"
  • 7. name="sa"></label><br> <br> <label><br><br> <input type="submit" name="b1" Value="INSERT"> <input type="reset" > </form> </body> </html> OUT PUT Now we will create an HTML form that can be used to add new records to the “MIS352" table. Here is the HTML form: © Yanbu University College 11 Insert Data From a Form Into a Database Inserting record 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 “Marks" table. Here is the "insert.php" page: © Yanbu University College Insert Data From a Form Into a Database(contd) Insert.php
  • 8. <?php // connect with the database and user in Php Myadmin $n=mysqli_connect("localhost","PHPClass","hello","MIS352"); if (mysqli_connect_errno()) { echo(" Error In connection"); } else { echo("database connected"); } $stuid=($_POST['sid']); $stuname=($_POST['sn']); $stumarks=intval($_POST['sa']); $sql="insert into Marks(STD_ID,STD_NAME,STD_MARKS) values ('$stuid','$stuname',$stumarks)"; if(mysqli_query($n,$sql)) {echo "<center><h1 style='color:aqua'>Record added successfully";} else {echo"error in insertion";} mysqli_close($n); ?> OUTPUT: © Yanbu University College PHP MySQL Select Select Data From a Database Table The SELECT statement is used to select data from a database. Syntax SELECT column_name(s) FROM table_name To get PHP to execute the statement above we must use the mysqli_query() function. This function is used to send a query
  • 9. or command to a MySQL connection. The example below stores the data returned by the mysql_query() function in the $result variable. Next, we use the mysqli_fetch_array() function to return the first row from the recordset as an array. Each call to mysqli_fetch_array() returns the next row in the recordset. The while loop loops through all the records in the recordset. To print the value of each row, we use the PHP $row variable ($row['FirstName'] and $row['LastName']). © Yanbu University College <?php echo "<h1 style='color:magenta'>The contents of Marks Table:</h1><br> <br>"; $con=mysqli_connect("localhost","PHPClass","hello","MIS352" ); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = mysqli_query($con,"SELECT * FROM Marks"); echo "<center> <table border='1'><tr> <th>STD_ID</th> <th>STD_NAME</th> <th>STD_MARKS</th> </tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['STD_ID'] . "</td>";
  • 10. echo "<td>" . $row['STD_NAME'] . "</td>"; echo "<td>" . $row['STD_MARKS'] . "</td>"; echo "</tr>"; } echo "</center></table>"; mysqli_close($con); ?> DATABASE CONNECTIVITY Complete example WITH mysqli_connect() © Yanbu University College <html><Head></head> <body><p> ID NAME EMAIL </p><br> <?php //connection to the database $con=mysqli_connect("localhost",”haseena",”husna","mis352"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } //execute the SQL query and return records $result = mysqli_query($con,"SELECT * FROM student"); //fetch tha data from the database while($row = mysqli_fetch_array($result)) { //display the results echo $row['ID'] . " " . $row['NAME']. " " . $row['EMAIL']; echo "<br />"; }
  • 11. //close the connection mysqli_close($con); ?> </body></html> DATABASE CONNECTIVITY Complete example WITH mysqli_connect() © Yanbu University College Output © Yanbu University College Die() Function Definition and Usage The die() function prints a message and exits the current script. This function is an alias of the exit() function. E.g. //connection to the database $dbhandle = mysql_connect(‘hostname’, ‘username’, ‘password’) or die("Unable to connect to MySQL"); © Yanbu University College DATABASE CONNECTIVITY WITH mysql_connect() <?php //connection to the database
  • 12. $dbhandle = mysql_connect(‘hostname’, ‘username’, ‘password’) or die("Unable to connect to MySQL"); echo "Connected to MySQL<br>"; //select a database to work with $selected = mysql_select_db("examples",$dbhandle) or die("Could not select examples"); //execute the SQL query and return records $result = mysql_query("SELECT id, model,year FROM cars"); //fetch tha data from the database while ($row = mysql_fetch_array($result)) { echo "ID:".$row{'id'}." Name:".$row{'model'}."Year: ". //display the results $row{'year'}."<br>"; } //close the connection mysql_close($dbhandle); ?> © Yanbu University College PHP MySQL The Where Clause <?php $con=mysqli_connect("localhost",”PHPClass",”hello","mis352" ); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = mysqli_query($con,"SELECT * FROM student
  • 13. WHERE NAME='hia' "); while($row = mysqli_fetch_array($result)) { echo $row['ID'] . " " . $row['NAME'] . " " . $row['EMAIL']; echo "<br>"; } ?> © Yanbu University College PHP MySQL Order By Keyword The ORDER BY Keyword The ORDER BY keyword is used to sort the data in a recordset in ascending order by default. If you want to sort the records in a descending order, you can use the DESC keyword <?php $con=mysqli_connect("localhost",”PHPClass",”Hello","mis352" ); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $result = mysqli_query($con,"SELECT * FROM student ORDER BY ID "); while($row = mysqli_fetch_array($result)) { echo $row['ID'] . " " . $row['NAME'] . " " . $row['EMAIL']; echo "<br>"; } ?>
  • 14. © Yanbu University College PHP MySQL Update The UPDATE statement is used to modify data in a table. <?php $con=mysqli_connect("localhost",”PHPClass",”Hello","mis352" ); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $b ="UPDATE student SET ID=36 WHERE NAME=‘Hasi' AND EMAIL=‘[email protected]'"; if (mysqli_query($con,$b)) { echo("RECORD UPDATED SUCCESFUL "); } ?> © Yanbu University College PHP MySQL Delete The DELETE FROM statement is used to delete records from a database table. <?php $con=mysqli_connect("localhost","PHPClass","hello","MIS352"
  • 15. ); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $a="DELETE FROM Marks WHERE STD_NAME='Malak'"; if (mysqli_query($con,$a)) { echo "1 record Deleted"; } else { echo "Error in Deletion the record: " . mysqli_error(); } mysqli_close($con); ?> OUTPUT: © Yanbu University College