SlideShare a Scribd company logo
1 of 18
Download to read offline
MySQL + PHP
What is MySQL?
• 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
• PHP 5 and later can work with a MySQL database using:
• MySQLi extension (the "i" stands for improved)
• PDO (PHP Data Objects)
• Three ways of working with PHP and MySQL:
• MySQLi (object-oriented)
• MySQLi (procedural)
• PDO
Basic MySQL Commands
• show databases;
• show tables;
• describe [table name];
• drop database [database name];
• drop table [table name];
Connection…
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Close the connection…
• mysqli_close($conn);
List Databases
// Usage without mysql_list_dbs()
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$res = mysql_query($conn, "SHOW DATABASES");
while ($row = mysql_fetch_assoc($res)) {
echo $row['Database'] . "n";
}
// Create database
$sql = "CREATE DATABASE myDB";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
}
Create Database
Create Table
// sql to create table
$sql = "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
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
Insert data in Table
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
Insert multiple
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com');";
$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com');";
$sql .= "INSERT INTO MyGuests (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);
}
Select data from table
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " .
$row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
Delete Data from Table
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
Update Data in Table
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
Some important methods to remember…
Function Description Usage
mysqli_autocommit() Turns on or off auto-committing
database modifications
mysqli_autocommit($con,FALSE)
mysqli_close() Closes a previously opened database
connection
mysqli_close($con)
mysqli_connect() Opens a new connection to the MySQL
server
mysqli_connect("localhost","my_user","my_password",
"my_db");
mysqli_connect_error() Returns the error description from the
last connection error
if (mysqli_connect_errno())
Some important methods to remember…
Function Description Usage
mysqli_query() Performs a query against
the database
mysqli_query($con,"SELECT * FROM Persons");
mysqli_query($con,"INSERT INTO Persons
(FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
mysqli_select_db() Changes the default
database for the connection
mysqli_select_db($con,"test");
mysqli_rollback() Rolls back the current
transaction for the database
mysqli_query($con,"INSERT INTO Persons
(FirstName,LastName,Age)
VALUES ('Glenn','Quagmire',33)");
mysqli_commit($con);
mysqli_rollback($con);
mysqli_real_escape_string() Escapes special characters in
a string for use in an SQL
statement
$firstname = mysqli_real_escape_string($con,
$_POST['firstname']);
$age = mysqli_real_escape_string($con, $_POST['age']);
$sql="INSERT INTO Persons (FirstName, Age)
VALUES ('$firstname', '$age')";
Some important methods to remember…
Function Description Usage
mysqli_fetch_array() Fetches a result row as an
associative, a numeric array, or
both
$sql="SELECT Lastname,Age FROM Persons ORDER BY
Lastname";
$result=mysqli_query($con,$sql);
$row=mysqli_fetch_array($result,MYSQLI_NUM);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)n",$row["Lastname"],$row["Age"]);
mysqli_fetch_assoc() Fetches a result row as an
associative array
$sql="SELECT Lastname,Age FROM Persons ORDER BY
Lastname";
$result=mysqli_query($con,$sql);
$row=mysqli_fetch_assoc($result);
printf ("%s (%s)n",$row["Lastname"],$row["Age"]);
mysqli_fetch_all() Fetches all result rows as an
associative array, a numeric
array, or both
$sql="SELECT Lastname,Age FROM Persons ORDER BY
Lastname";
$result=mysqli_query($con,$sql);
mysqli_fetch_all($result,MYSQLI_ASSOC);
mysqli_data_seek() Adjusts the result pointer to an
arbitrary row in the result-set
$result=mysqli_query($con,$sql)
mysqli_data_seek($result,14);
$row=mysqli_fetch_row($result);
Some important methods to remember…
Function Description Usage
mysqli_fetch_row() Fetches one row from a result-
set and returns it as an
enumerated array
if ($result=mysqli_query($con,$sql))
{
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
printf ("%s (%s)n",$row[0],$row[1]);
}
mysqli_free_result($result);}
mysqli_field_count() Returns the number of columns
for the most recent query
mysqli_query($con,"SELECT * FROM Friends");
mysqli_field_count($con);
mysqli_num_fields() Returns the number of fields in
a result set
if ($result=mysqli_query($con,$sql))
{
$fieldcount=mysqli_num_fields($result);
mysqli_num_rows() Returns the number of rows in a
result set
$rowcount=mysqli_num_rows($result);

More Related Content

What's hot

What's hot (20)

html-table
html-tablehtml-table
html-table
 
php
phpphp
php
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Jquery
JqueryJquery
Jquery
 
Html
HtmlHtml
Html
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Php array
Php arrayPhp array
Php array
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
PHP Security
PHP SecurityPHP Security
PHP Security
 
Html ppt
Html pptHtml ppt
Html ppt
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScript
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
 
PHP slides
PHP slidesPHP slides
PHP slides
 
Laravel ppt
Laravel pptLaravel ppt
Laravel ppt
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Html
HtmlHtml
Html
 
Lesson 2 php data types
Lesson 2   php data typesLesson 2   php data types
Lesson 2 php data types
 

Similar to 4.3 MySQL + PHP

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 MySQLArti Parab Academics
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesRasan Samarasinghe
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDatabase Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDhivyaa C.R
 
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
 
Stored Procedure
Stored ProcedureStored Procedure
Stored ProcedureNidiaRamirez07
 
Web Application Development using PHP Chapter 7
Web Application Development using PHP Chapter 7Web Application Development using PHP Chapter 7
Web Application Development using PHP Chapter 7Mohd Harris Ahmad Jaal
 
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 sqlsaritasingh19866
 
Connecting_to_Database(MySQL)_in_PHP.pptx
Connecting_to_Database(MySQL)_in_PHP.pptxConnecting_to_Database(MySQL)_in_PHP.pptx
Connecting_to_Database(MySQL)_in_PHP.pptxTempMail233488
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxPHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxCynthiaKendi1
 
Database presentation
Database presentationDatabase presentation
Database presentationwebhostingguy
 
Chapter 3.1.pptx
Chapter 3.1.pptxChapter 3.1.pptx
Chapter 3.1.pptxmebratu9
 
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 NewbiesDave Stokes
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2ADARSH BHATT
 
Web Application Development using PHP Chapter 8
Web Application Development using PHP Chapter 8Web Application Development using PHP Chapter 8
Web Application Development using PHP Chapter 8Mohd Harris Ahmad Jaal
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erickokelloerick
 

Similar to 4.3 MySQL + PHP (20)

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
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
Mysql & Php
Mysql & PhpMysql & Php
Mysql & Php
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
 
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering CollegeDatabase Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
Database Connectivity MYSQL by Dr.C.R.Dhivyaa Kongu Engineering College
 
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
 
Stored Procedure
Stored ProcedureStored Procedure
Stored Procedure
 
Web Application Development using PHP Chapter 7
Web Application Development using PHP Chapter 7Web Application Development using PHP Chapter 7
Web Application Development using PHP Chapter 7
 
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
 
Connecting_to_Database(MySQL)_in_PHP.pptx
Connecting_to_Database(MySQL)_in_PHP.pptxConnecting_to_Database(MySQL)_in_PHP.pptx
Connecting_to_Database(MySQL)_in_PHP.pptx
 
PHP with MySQL
PHP with MySQLPHP with MySQL
PHP with MySQL
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxPHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptx
 
Database presentation
Database presentationDatabase presentation
Database presentation
 
Chapter 3.1.pptx
Chapter 3.1.pptxChapter 3.1.pptx
Chapter 3.1.pptx
 
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
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
Php mysq
Php mysqPhp mysq
Php mysq
 
Web Application Development using PHP Chapter 8
Web Application Development using PHP Chapter 8Web Application Development using PHP Chapter 8
Web Application Development using PHP Chapter 8
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
 

More from Jalpesh Vasa

Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Jalpesh Vasa
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Jalpesh Vasa
 
4.4 PHP Session
4.4 PHP Session4.4 PHP Session
4.4 PHP SessionJalpesh Vasa
 
4.2 PHP Function
4.2 PHP Function4.2 PHP Function
4.2 PHP FunctionJalpesh Vasa
 
4.1 PHP Arrays
4.1 PHP Arrays4.1 PHP Arrays
4.1 PHP ArraysJalpesh Vasa
 
3.2.1 javascript regex example
3.2.1 javascript regex example3.2.1 javascript regex example
3.2.1 javascript regex exampleJalpesh Vasa
 
3.2 javascript regex
3.2 javascript regex3.2 javascript regex
3.2 javascript regexJalpesh Vasa
 
3. Java Script
3. Java Script3. Java Script
3. Java ScriptJalpesh Vasa
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOMJalpesh Vasa
 
2 introduction css
2 introduction css2 introduction css
2 introduction cssJalpesh Vasa
 
1 web technologies
1 web technologies1 web technologies
1 web technologiesJalpesh Vasa
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVAJalpesh Vasa
 
Kotlin for android development
Kotlin for android developmentKotlin for android development
Kotlin for android developmentJalpesh Vasa
 
Security in php
Security in phpSecurity in php
Security in phpJalpesh Vasa
 

More from Jalpesh Vasa (16)

Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
 
Object Oriented PHP - PART-2
Object Oriented PHP - PART-2Object Oriented PHP - PART-2
Object Oriented PHP - PART-2
 
5. HTML5
5. HTML55. HTML5
5. HTML5
 
4.4 PHP Session
4.4 PHP Session4.4 PHP Session
4.4 PHP Session
 
4.2 PHP Function
4.2 PHP Function4.2 PHP Function
4.2 PHP Function
 
4.1 PHP Arrays
4.1 PHP Arrays4.1 PHP Arrays
4.1 PHP Arrays
 
4 Basic PHP
4 Basic PHP4 Basic PHP
4 Basic PHP
 
3.2.1 javascript regex example
3.2.1 javascript regex example3.2.1 javascript regex example
3.2.1 javascript regex example
 
3.2 javascript regex
3.2 javascript regex3.2 javascript regex
3.2 javascript regex
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
 
2 introduction css
2 introduction css2 introduction css
2 introduction css
 
1 web technologies
1 web technologies1 web technologies
1 web technologies
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVA
 
Kotlin for android development
Kotlin for android developmentKotlin for android development
Kotlin for android development
 
Security in php
Security in phpSecurity in php
Security in php
 

Recently uploaded

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
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
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
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 

Recently uploaded (20)

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
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
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
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"Rapple "Scholarly Communications and the Sustainable Development Goals"
Rapple "Scholarly Communications and the Sustainable Development Goals"
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 

4.3 MySQL + PHP

  • 2. What is MySQL? • 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
  • 3. • PHP 5 and later can work with a MySQL database using: • MySQLi extension (the "i" stands for improved) • PDO (PHP Data Objects) • Three ways of working with PHP and MySQL: • MySQLi (object-oriented) • MySQLi (procedural) • PDO
  • 4. Basic MySQL Commands • show databases; • show tables; • describe [table name]; • drop database [database name]; • drop table [table name];
  • 5. Connection… <?php $servername = "localhost"; $username = "username"; $password = "password"; // Create connection $conn = mysqli_connect($servername, $username, $password); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; ?>
  • 6. Close the connection… • mysqli_close($conn);
  • 7. List Databases // Usage without mysql_list_dbs() $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $res = mysql_query($conn, "SHOW DATABASES"); while ($row = mysql_fetch_assoc($res)) { echo $row['Database'] . "n"; }
  • 8. // Create database $sql = "CREATE DATABASE myDB"; if (mysqli_query($conn, $sql)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysqli_error($conn); } Create Database
  • 9. Create Table // sql to create table $sql = "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 )"; if (mysqli_query($conn, $sql)) { echo "Table MyGuests created successfully"; } else { echo "Error creating table: " . mysqli_error($conn); }
  • 10. Insert data in Table $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; }
  • 11. Insert multiple $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com');"; $sql .= "INSERT INTO MyGuests (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); }
  • 12. Select data from table $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; } } else { echo "0 results"; }
  • 13. Delete Data from Table // sql to delete a record $sql = "DELETE FROM MyGuests WHERE id=3"; if (mysqli_query($conn, $sql)) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($conn); }
  • 14. Update Data in Table $sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2"; if (mysqli_query($conn, $sql)) { echo "Record updated successfully"; } else { echo "Error updating record: " . mysqli_error($conn); }
  • 15. Some important methods to remember… Function Description Usage mysqli_autocommit() Turns on or off auto-committing database modifications mysqli_autocommit($con,FALSE) mysqli_close() Closes a previously opened database connection mysqli_close($con) mysqli_connect() Opens a new connection to the MySQL server mysqli_connect("localhost","my_user","my_password", "my_db"); mysqli_connect_error() Returns the error description from the last connection error if (mysqli_connect_errno())
  • 16. Some important methods to remember… Function Description Usage mysqli_query() Performs a query against the database mysqli_query($con,"SELECT * FROM Persons"); mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)"); mysqli_select_db() Changes the default database for the connection mysqli_select_db($con,"test"); mysqli_rollback() Rolls back the current transaction for the database mysqli_query($con,"INSERT INTO Persons (FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)"); mysqli_commit($con); mysqli_rollback($con); mysqli_real_escape_string() Escapes special characters in a string for use in an SQL statement $firstname = mysqli_real_escape_string($con, $_POST['firstname']); $age = mysqli_real_escape_string($con, $_POST['age']); $sql="INSERT INTO Persons (FirstName, Age) VALUES ('$firstname', '$age')";
  • 17. Some important methods to remember… Function Description Usage mysqli_fetch_array() Fetches a result row as an associative, a numeric array, or both $sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; $result=mysqli_query($con,$sql); $row=mysqli_fetch_array($result,MYSQLI_NUM); $row=mysqli_fetch_array($result,MYSQLI_ASSOC); printf ("%s (%s)n",$row["Lastname"],$row["Age"]); mysqli_fetch_assoc() Fetches a result row as an associative array $sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; $result=mysqli_query($con,$sql); $row=mysqli_fetch_assoc($result); printf ("%s (%s)n",$row["Lastname"],$row["Age"]); mysqli_fetch_all() Fetches all result rows as an associative array, a numeric array, or both $sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname"; $result=mysqli_query($con,$sql); mysqli_fetch_all($result,MYSQLI_ASSOC); mysqli_data_seek() Adjusts the result pointer to an arbitrary row in the result-set $result=mysqli_query($con,$sql) mysqli_data_seek($result,14); $row=mysqli_fetch_row($result);
  • 18. Some important methods to remember… Function Description Usage mysqli_fetch_row() Fetches one row from a result- set and returns it as an enumerated array if ($result=mysqli_query($con,$sql)) { // Fetch one and one row while ($row=mysqli_fetch_row($result)) { printf ("%s (%s)n",$row[0],$row[1]); } mysqli_free_result($result);} mysqli_field_count() Returns the number of columns for the most recent query mysqli_query($con,"SELECT * FROM Friends"); mysqli_field_count($con); mysqli_num_fields() Returns the number of fields in a result set if ($result=mysqli_query($con,$sql)) { $fieldcount=mysqli_num_fields($result); mysqli_num_rows() Returns the number of rows in a result set $rowcount=mysqli_num_rows($result);