SlideShare une entreprise Scribd logo
1  sur  18
Télécharger pour lire hors ligne
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);

Contenu connexe

Tendances

JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions Reem Alattas
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredDanish Mehraj
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - OperatorsWebStackAcademy
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPsRavi Bhadauria
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts Bharat Kalia
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps Hitesh-Java
 
collection framework in java
collection framework in javacollection framework in java
collection framework in javaMANOJ KUMAR
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesGanesh Samarthyam
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & ArraysHenry Osborne
 

Tendances (20)

JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
 
Introduction to sql
Introduction to sqlIntroduction to sql
Introduction to sql
 
SQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics CoveredSQL Complete Tutorial. All Topics Covered
SQL Complete Tutorial. All Topics Covered
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
Chapter8 pl sql
Chapter8 pl sqlChapter8 pl sql
Chapter8 pl sql
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Java interface
Java interfaceJava interface
Java interface
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 

Similaire à 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
 
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
 
The Ring programming language version 1.10 book - Part 37 of 212
The Ring programming language version 1.10 book - Part 37 of 212The Ring programming language version 1.10 book - Part 37 of 212
The Ring programming language version 1.10 book - Part 37 of 212Mahmoud Samir Fayed
 

Similaire à 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 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
 
The Ring programming language version 1.10 book - Part 37 of 212
The Ring programming language version 1.10 book - Part 37 of 212The Ring programming language version 1.10 book - Part 37 of 212
The Ring programming language version 1.10 book - Part 37 of 212
 

Plus de 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
 
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.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
 

Plus de 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
 

Dernier

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
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
 
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
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
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
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 

Dernier (20)

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
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
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
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
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 

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);