SlideShare a Scribd company logo
1 of 12
Connecting to Database(MySQL)
in PHP
Create a Connection with DB:
• By using PHP,we can able to connect with database(MySQL).
• In order to connect with database, we need three parameters
 Hostname(ServerName) (By default “localhost”)
 Username (By default “root”)
 Password (By default “No Password”)
• In PHP, we have one inbuilt function to create connection with database(MySQL)
.i.e.,
– mysqli_connect(hostname,username,password)
• This function creates a successful connection with DB if you provide valid
information.
• When the connection is not well we can kill that connection by using
– die(“Can’t create connection”);
• mysqli_close() function is used to disconnect with MySQL database.
Example:
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully';
mysqli_close($conn);
?>
Execute Queries:
Create a Database:
• After creating connection we need to create a database .
• PHP has one in built function to perform different operations
(create (db &table),insert,update and delete) on database.i.e.,
– mysqli_query(connection,query)
• It has two parameters, those are
– Connection :name of the connection
– Query: specifies the query
Example:
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
$sql = 'CREATE DATABASE CollegeDb';
if(mysqli_query( $conn,$sql))
{
echo "Database created successfully.";
}
else
{
echo "Sorry, database creation failed ".mysqli_error($conn);
}
mysqli_close($conn);
?>
Creating a Table
• After creating database, we need to create
table.
• In PHP, mysqli_query() function is used to
create a table.
Example
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname='CollegeDb';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo "Connected successfully <br/>“;
$sql = "create table students(Sid INT,Sname VARCHAR(20),Age INT)";
if(mysqli_query($conn, $sql)){
echo "Table students created successfully";
}else{
echo "Could not create table: ". mysqli_error($conn);
}
mysqli_close($conn);
?>
Insert Record into Table
• After creating table, we need to insert
data(records) into table.
• In PHP, mysqli_query() function is used to
insert record into table.
Example
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname='CollegeDb';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully‘;
$sql = 'INSERT INTO students VALUES (521,"Madhu", 30)';
if(mysqli_query($conn, $sql)){
echo "Record inserted successfully";
}else{
echo "Could not insert record: ". mysqli_error($conn);
}
mysqli_close($conn);
?>
Delete Record
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname='CollegeDb';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected successfully‘;
$id=521;
$sql = “delete from students where sid=$id" ;
if(mysqli_query($conn, $sql)){
echo "Record inserted successfully";
}else{
echo "Could not insert record: ". mysqli_error($conn);
}
mysqli_close($conn);
?>
Select data from Table
• In PHP, mysqli_query() function is used to retrieve
data from table.
• There are two other MySQLi functions used in
select query.
– mysqli_num_rows(mysqli_result $result): returns
number of rows.
– mysqli_fetch_assoc(mysqli_result $result): returns
row as an associative array. Each key of the array
represents the column name of the table. It return
NULL if there are no more rows.
Example:
$sql = 'SELECT * FROM students';
$retval=mysqli_query($conn, $sql);
if(mysqli_num_rows($retval) > 0)
{
while($row = mysqli_fetch_assoc($retval))
{
echo "Student ID :".$row['sid']."<br> ";
echo "Student NAME :". $row['sname']."<br> ";
echo "Student Age :". $row['age']." <br> ";
echo "--------------------------------<br>";
} //end of while
}
else
{
echo "0 results";
}
mysqli_close($conn);

More Related Content

Similar to Connecting_to_Database(MySQL)_in_PHP.pptx

Pemrograman Web 8 - MySQL
Pemrograman Web 8 - MySQLPemrograman Web 8 - MySQL
Pemrograman Web 8 - MySQLNur Fadli Utomo
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesRasan Samarasinghe
 
Practical MySQL.pptx
Practical MySQL.pptxPractical MySQL.pptx
Practical MySQL.pptxHussainUsman4
 
PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part IIFirdaus Adib
 
Intro to php
Intro to phpIntro to php
Intro to phpSp Singh
 
HOW TO UPLOAD AND DISPLAY IMAGE PHP HTML SQL
HOW TO UPLOAD AND DISPLAY IMAGE PHP HTML SQLHOW TO UPLOAD AND DISPLAY IMAGE PHP HTML SQL
HOW TO UPLOAD AND DISPLAY IMAGE PHP HTML SQLmauricemuteti2015
 
LAMP_TRAINING_SESSION_8
LAMP_TRAINING_SESSION_8LAMP_TRAINING_SESSION_8
LAMP_TRAINING_SESSION_8umapst
 
Php 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodPhp 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodJeremy Kendall
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
Object oriented mysqli connection function
Object oriented mysqli connection functionObject oriented mysqli connection function
Object oriented mysqli connection functionclickon2010
 
CRUD OPERATIONS using MySQL connectivity in php
CRUD OPERATIONS using MySQL connectivity in phpCRUD OPERATIONS using MySQL connectivity in php
CRUD OPERATIONS using MySQL connectivity in phpKavithaK23
 
P H P Part I I, By Kian
P H P  Part  I I,  By  KianP H P  Part  I I,  By  Kian
P H P Part I I, By Kianphelios
 

Similar to Connecting_to_Database(MySQL)_in_PHP.pptx (20)

Pemrograman Web 8 - MySQL
Pemrograman Web 8 - MySQLPemrograman Web 8 - MySQL
Pemrograman Web 8 - MySQL
 
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
 
Practical MySQL.pptx
Practical MySQL.pptxPractical MySQL.pptx
Practical MySQL.pptx
 
Php talk
Php talkPhp talk
Php talk
 
PHP - Getting good with MySQL part II
 PHP - Getting good with MySQL part II PHP - Getting good with MySQL part II
PHP - Getting good with MySQL part II
 
Intro to php
Intro to phpIntro to php
Intro to php
 
Stored Procedure
Stored ProcedureStored Procedure
Stored Procedure
 
Coding for php with mysql
Coding for php with mysqlCoding for php with mysql
Coding for php with mysql
 
HOW TO UPLOAD AND DISPLAY IMAGE PHP HTML SQL
HOW TO UPLOAD AND DISPLAY IMAGE PHP HTML SQLHOW TO UPLOAD AND DISPLAY IMAGE PHP HTML SQL
HOW TO UPLOAD AND DISPLAY IMAGE PHP HTML SQL
 
My_sql_with_php
My_sql_with_phpMy_sql_with_php
My_sql_with_php
 
LAMP_TRAINING_SESSION_8
LAMP_TRAINING_SESSION_8LAMP_TRAINING_SESSION_8
LAMP_TRAINING_SESSION_8
 
Php
PhpPhp
Php
 
Php 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the GoodPhp 102: Out with the Bad, In with the Good
Php 102: Out with the Bad, In with the Good
 
More Php
More PhpMore Php
More Php
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Object oriented mysqli connection function
Object oriented mysqli connection functionObject oriented mysqli connection function
Object oriented mysqli connection function
 
CRUD OPERATIONS using MySQL connectivity in php
CRUD OPERATIONS using MySQL connectivity in phpCRUD OPERATIONS using MySQL connectivity in php
CRUD OPERATIONS using MySQL connectivity in php
 
Php mysq
Php mysqPhp mysq
Php mysq
 
P H P Part I I, By Kian
P H P  Part  I I,  By  KianP H P  Part  I I,  By  Kian
P H P Part I I, By Kian
 

Recently uploaded

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 

Recently uploaded (20)

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 

Connecting_to_Database(MySQL)_in_PHP.pptx

  • 2. Create a Connection with DB: • By using PHP,we can able to connect with database(MySQL). • In order to connect with database, we need three parameters  Hostname(ServerName) (By default “localhost”)  Username (By default “root”)  Password (By default “No Password”) • In PHP, we have one inbuilt function to create connection with database(MySQL) .i.e., – mysqli_connect(hostname,username,password) • This function creates a successful connection with DB if you provide valid information. • When the connection is not well we can kill that connection by using – die(“Can’t create connection”); • mysqli_close() function is used to disconnect with MySQL database.
  • 3. Example: <?php $host = 'localhost'; $user = 'root'; $pass = ''; $conn = mysqli_connect($host, $user, $pass); if(! $conn ) { die('Could not connect: ' . mysqli_error()); } echo 'Connected successfully'; mysqli_close($conn); ?>
  • 4. Execute Queries: Create a Database: • After creating connection we need to create a database . • PHP has one in built function to perform different operations (create (db &table),insert,update and delete) on database.i.e., – mysqli_query(connection,query) • It has two parameters, those are – Connection :name of the connection – Query: specifies the query
  • 5. Example: <?php $host = 'localhost'; $user = 'root'; $pass = ''; $conn = mysqli_connect($host, $user, $pass); if(! $conn ) { die('Could not connect: ' . mysqli_error()); } $sql = 'CREATE DATABASE CollegeDb'; if(mysqli_query( $conn,$sql)) { echo "Database created successfully."; } else { echo "Sorry, database creation failed ".mysqli_error($conn); } mysqli_close($conn); ?>
  • 6. Creating a Table • After creating database, we need to create table. • In PHP, mysqli_query() function is used to create a table.
  • 7. Example <?php $host = 'localhost'; $user = 'root'; $pass = ''; $dbname='CollegeDb'; $conn = mysqli_connect($host, $user, $pass,$dbname); if(! $conn ) { die('Could not connect: ' . mysqli_error()); } echo "Connected successfully <br/>“; $sql = "create table students(Sid INT,Sname VARCHAR(20),Age INT)"; if(mysqli_query($conn, $sql)){ echo "Table students created successfully"; }else{ echo "Could not create table: ". mysqli_error($conn); } mysqli_close($conn); ?>
  • 8. Insert Record into Table • After creating table, we need to insert data(records) into table. • In PHP, mysqli_query() function is used to insert record into table.
  • 9. Example <?php $host = 'localhost'; $user = 'root'; $pass = ''; $dbname='CollegeDb'; $conn = mysqli_connect($host, $user, $pass,$dbname); if(! $conn ) { die('Could not connect: ' . mysqli_error()); } echo 'Connected successfully‘; $sql = 'INSERT INTO students VALUES (521,"Madhu", 30)'; if(mysqli_query($conn, $sql)){ echo "Record inserted successfully"; }else{ echo "Could not insert record: ". mysqli_error($conn); } mysqli_close($conn); ?>
  • 10. Delete Record <?php $host = 'localhost'; $user = 'root'; $pass = ''; $dbname='CollegeDb'; $conn = mysqli_connect($host, $user, $pass,$dbname); if(! $conn ) { die('Could not connect: ' . mysqli_error()); } echo 'Connected successfully‘; $id=521; $sql = “delete from students where sid=$id" ; if(mysqli_query($conn, $sql)){ echo "Record inserted successfully"; }else{ echo "Could not insert record: ". mysqli_error($conn); } mysqli_close($conn); ?>
  • 11. Select data from Table • In PHP, mysqli_query() function is used to retrieve data from table. • There are two other MySQLi functions used in select query. – mysqli_num_rows(mysqli_result $result): returns number of rows. – mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array. Each key of the array represents the column name of the table. It return NULL if there are no more rows.
  • 12. Example: $sql = 'SELECT * FROM students'; $retval=mysqli_query($conn, $sql); if(mysqli_num_rows($retval) > 0) { while($row = mysqli_fetch_assoc($retval)) { echo "Student ID :".$row['sid']."<br> "; echo "Student NAME :". $row['sname']."<br> "; echo "Student Age :". $row['age']." <br> "; echo "--------------------------------<br>"; } //end of while } else { echo "0 results"; } mysqli_close($conn);