SlideShare a Scribd company logo
1 of 17
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
National Diploma in Information and Communication Technology
PHP :3-PHP-CONNECT-TO-MySQL>
K72C001M07 - Web Programming
Y. Achchuthan
Department of Information & Communication Technology,
Sri Lanka – German Training Institute
11/23/2018 3-PHP-CONNECT-TO-MySQL 1
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
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
11/23/2018 3-PHP-CONNECT-TO-MySQL 2
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Connect to MySQL
• Open a Connection to MySQL
• Syantax
$con = mysqli_connect(host,username,password,dbname,port,socket);
Return Value: Returns an object representing the connection to the MySQL
server
11/23/2018 3-PHP-CONNECT-TO-MySQL 3
Parameter Description
host Optional. Specifies a host name or an IP address
username Optional. Specifies the MySQL username
password Optional. Specifies the MySQL password
dbname Optional. Specifies the default database to be used
port Optional. Specifies the port number to attempt to connect to the MySQL
server
socket Optional. Specifies the socket or named pipe to be used
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Closing a Connection
• Close the created database connection as follows
mysql_close($con);
11/23/2018 3-PHP-CONNECT-TO-MySQL 4
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Example - mysqli_connect()
//config.php
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','');
$conn=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME)
;
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " .
mysqli_connect_error();
}
echo "Connected successfully";
11/23/2018 3-PHP-CONNECT-TO-MySQL 5
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
mysqli_query() Function
• Perform queries against the database:
• Syntax
mysqli_query(connection,query,resultmode);
11/23/2018 3-PHP-CONNECT-TO-MySQL 6
Parameter Description
connection Required. Specifies the MySQL connection to use
query Required. Specifies the query string
resultmode Optional. A constant. Either:
•MYSQLI_USE_RESULT (Use this if we have to retrieve large amount of
data)
•MYSQLI_STORE_RESULT (This is default)
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Create a MySQL Database
$sql = "CREATE DATABASE NVQ5";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " .
mysqli_error($conn);
}
11/23/2018 3-PHP-CONNECT-TO-MySQL 7
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Create MySQL Tables
$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);
}
11/23/2018 3-PHP-CONNECT-TO-MySQL 8
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Notes on the table above
• NOT NULL - Each row must contain a value for that column, null
values are not allowed
• DEFAULT value - Set a default value that is added when no other
value is passed
• UNSIGNED - Used for number types, limits the stored data to positive
numbers and zero
• AUTO INCREMENT - MySQL automatically increases the value of the
field by 1 each time a new record is added
• PRIMARY KEY - Used to uniquely identify the rows in a table. The
column with PRIMARY KEY setting is often an ID number, and is often
used with AUTO_INCREMENT
11/23/2018 3-PHP-CONNECT-TO-MySQL 9
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Insert Data Into MySQL
After a database and a table have been created, we can start adding
data in them.
• Here are some syntax rules to follow:
• The SQL query must be quoted in PHP
• String values inside the SQL query must be quoted
• Numeric values must not be quoted
• The word NULL must not be quoted
Note: I f a column is AUTO_INCREMENT (like the "id" column) or
TIMESTAMP (like the "reg_date" column), it is no need to be specified
in the SQL query; MySQL will automatically add the value.
11/23/2018 3-PHP-CONNECT-TO-MySQL 10
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Insert Data Into MySQL
$sql = "INSERT INTO MyGuests (firstname,
lastname, email) VALUES ('John', 'Doe',
'john@example.com')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" .
mysqli_error($conn);
}
11/23/2018 3-PHP-CONNECT-TO-MySQL 11
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Insert Multiple Records Into MySQL
$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);
}
11/23/2018 3-PHP-CONNECT-TO-MySQL 12
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Select Data From a MySQL
$sql = "SELECT * FROM MyGuests";
//$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)) {
//var_dump($row);
echo "id: " . $row["id"]. " - Name: " .
$row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
11/23/2018 3-PHP-CONNECT-TO-MySQL 13
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Delete Data From a MySQL
$sql = "DELETE FROM MyGuests WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " .
mysqli_error($conn);
}
11/23/2018 3-PHP-CONNECT-TO-MySQL 14
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Update Data In a MySQL
$sql = "UPDATE MyGuests SET lastname='Mugund'
WHERE id=9";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " .
mysqli_error($conn);
}
11/23/2018 3-PHP-CONNECT-TO-MySQL 15
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Limit Data Selections From a MySQL
$sql = "SELECT * FROM MyGuests ORDER BY id ASC LIMIT
10 OFFSET 15";
//$sql = "SELECT * FROM MyGuests ORDER BY id ASC
LIMIT 10 OFFSET 10";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " .
$row["firstname"]. " " . $row["lastname"].
"<br>";
}
} else {
echo "0 results";
}
Note: The SQL query above says "return only 10 records, start on record 16 (OFFSET 15)":
11/23/2018 3-PHP-CONNECT-TO-MySQL 16
Sri Lanka-German Training InstituteDepartment of Information and Communication Technology
Reference
www.w3schools.com
www.php.net
www.slgti.com
Friday, November 23, 2018 17

More Related Content

Similar to 3 php-connect-to-my sql

Develop Python Applications with MySQL Connector/Python
Develop Python Applications with MySQL Connector/PythonDevelop Python Applications with MySQL Connector/Python
Develop Python Applications with MySQL Connector/PythonJesper Wisborg Krogh
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sqlsalissal
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbaiaadi Surve
 
MySQL server security
MySQL server securityMySQL server security
MySQL server securityDamien Seguy
 
Agile Data Science 2.0
Agile Data Science 2.0Agile Data Science 2.0
Agile Data Science 2.0Russell Jurney
 
SQLSecurity.ppt
SQLSecurity.pptSQLSecurity.ppt
SQLSecurity.pptCNSHacking
 
SQLSecurity.ppt
SQLSecurity.pptSQLSecurity.ppt
SQLSecurity.pptLokeshK66
 
NoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices -  Michael HacksteinNoSQL meets Microservices -  Michael Hackstein
NoSQL meets Microservices - Michael Hacksteindistributed matters
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHPTaha Malampatti
 
Php and MySQL Web Development
Php and MySQL Web DevelopmentPhp and MySQL Web Development
Php and MySQL Web Developmentw3ondemand
 
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxModule 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxmoirarandell
 
MySQL NoSQL JSON JS Python "Document Store" demo
MySQL NoSQL JSON JS Python "Document Store" demoMySQL NoSQL JSON JS Python "Document Store" demo
MySQL NoSQL JSON JS Python "Document Store" demoKeith Hollman
 
Agile Data Science 2.0
Agile Data Science 2.0Agile Data Science 2.0
Agile Data Science 2.0Russell Jurney
 
DEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lampDEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lampFelipe Prado
 
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScriptJavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScriptDave Stokes
 
Agile Data Science 2.0
Agile Data Science 2.0Agile Data Science 2.0
Agile Data Science 2.0Russell Jurney
 

Similar to 3 php-connect-to-my sql (20)

Develop Python Applications with MySQL Connector/Python
Develop Python Applications with MySQL Connector/PythonDevelop Python Applications with MySQL Connector/Python
Develop Python Applications with MySQL Connector/Python
 
Mysql
MysqlMysql
Mysql
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
 
MySQL server security
MySQL server securityMySQL server security
MySQL server security
 
Agile Data Science 2.0
Agile Data Science 2.0Agile Data Science 2.0
Agile Data Science 2.0
 
SQLSecurity.ppt
SQLSecurity.pptSQLSecurity.ppt
SQLSecurity.ppt
 
SQLSecurity.ppt
SQLSecurity.pptSQLSecurity.ppt
SQLSecurity.ppt
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 
NoSQL meets Microservices - Michael Hackstein
NoSQL meets Microservices -  Michael HacksteinNoSQL meets Microservices -  Michael Hackstein
NoSQL meets Microservices - Michael Hackstein
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Agile Data Science
Agile Data ScienceAgile Data Science
Agile Data Science
 
Php and MySQL Web Development
Php and MySQL Web DevelopmentPhp and MySQL Web Development
Php and MySQL Web Development
 
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docxModule 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
Module 6WEB SERVER AND SERVER SIDE SCRPTING, PART-2Chapte.docx
 
MySQL NoSQL JSON JS Python "Document Store" demo
MySQL NoSQL JSON JS Python "Document Store" demoMySQL NoSQL JSON JS Python "Document Store" demo
MySQL NoSQL JSON JS Python "Document Store" demo
 
Agile Data Science 2.0
Agile Data Science 2.0Agile Data Science 2.0
Agile Data Science 2.0
 
DEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lampDEFCON 23 - Lance buttars Nemus - sql injection on lamp
DEFCON 23 - Lance buttars Nemus - sql injection on lamp
 
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScriptJavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
 
Agile Data Science 2.0
Agile Data Science 2.0Agile Data Science 2.0
Agile Data Science 2.0
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 

More from Achchuthan Yogarajah

More from Achchuthan Yogarajah (11)

Managing the design process
Managing the design processManaging the design process
Managing the design process
 
intoduction to network devices
intoduction to network devicesintoduction to network devices
intoduction to network devices
 
basic network concepts
basic network conceptsbasic network concepts
basic network concepts
 
4 php-advanced
4 php-advanced4 php-advanced
4 php-advanced
 
PHP Form Handling
PHP Form HandlingPHP Form Handling
PHP Form Handling
 
PHP-introduction
PHP-introductionPHP-introduction
PHP-introduction
 
Introduction to Web Programming
Introduction to Web Programming Introduction to Web Programming
Introduction to Web Programming
 
Language Localisation of Tamil using Statistical Machine Translation - ICTer2015
Language Localisation of Tamil using Statistical Machine Translation - ICTer2015Language Localisation of Tamil using Statistical Machine Translation - ICTer2015
Language Localisation of Tamil using Statistical Machine Translation - ICTer2015
 
PADDY CULTIVATION MANAGEMENT SYSTEM
PADDY CULTIVATION MANAGEMENT  SYSTEMPADDY CULTIVATION MANAGEMENT  SYSTEM
PADDY CULTIVATION MANAGEMENT SYSTEM
 
Statistical Machine Translation for Language Localisation
Statistical Machine Translation for Language LocalisationStatistical Machine Translation for Language Localisation
Statistical Machine Translation for Language Localisation
 
Greedy Knapsack Problem - by Y Achchuthan
Greedy Knapsack Problem  - by Y AchchuthanGreedy Knapsack Problem  - by Y Achchuthan
Greedy Knapsack Problem - by Y Achchuthan
 

Recently uploaded

Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
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
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
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
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
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
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
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
 
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
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
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
 
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
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 

Recently uploaded (20)

Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
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
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
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
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
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
 
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
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
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
 
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
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
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
 
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
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 

3 php-connect-to-my sql

  • 1. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology National Diploma in Information and Communication Technology PHP :3-PHP-CONNECT-TO-MySQL> K72C001M07 - Web Programming Y. Achchuthan Department of Information & Communication Technology, Sri Lanka – German Training Institute 11/23/2018 3-PHP-CONNECT-TO-MySQL 1
  • 2. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology 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 11/23/2018 3-PHP-CONNECT-TO-MySQL 2
  • 3. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Connect to MySQL • Open a Connection to MySQL • Syantax $con = mysqli_connect(host,username,password,dbname,port,socket); Return Value: Returns an object representing the connection to the MySQL server 11/23/2018 3-PHP-CONNECT-TO-MySQL 3 Parameter Description host Optional. Specifies a host name or an IP address username Optional. Specifies the MySQL username password Optional. Specifies the MySQL password dbname Optional. Specifies the default database to be used port Optional. Specifies the port number to attempt to connect to the MySQL server socket Optional. Specifies the socket or named pipe to be used
  • 4. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Closing a Connection • Close the created database connection as follows mysql_close($con); 11/23/2018 3-PHP-CONNECT-TO-MySQL 4
  • 5. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Example - mysqli_connect() //config.php define('DB_HOST','localhost'); define('DB_USER','root'); define('DB_PASS',''); define('DB_NAME',''); $conn=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME) ; if (mysqli_connect_errno()){ echo "Failed to connect to MySQL: " . mysqli_connect_error(); } echo "Connected successfully"; 11/23/2018 3-PHP-CONNECT-TO-MySQL 5
  • 6. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology mysqli_query() Function • Perform queries against the database: • Syntax mysqli_query(connection,query,resultmode); 11/23/2018 3-PHP-CONNECT-TO-MySQL 6 Parameter Description connection Required. Specifies the MySQL connection to use query Required. Specifies the query string resultmode Optional. A constant. Either: •MYSQLI_USE_RESULT (Use this if we have to retrieve large amount of data) •MYSQLI_STORE_RESULT (This is default)
  • 7. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Create a MySQL Database $sql = "CREATE DATABASE NVQ5"; if (mysqli_query($conn, $sql)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysqli_error($conn); } 11/23/2018 3-PHP-CONNECT-TO-MySQL 7
  • 8. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Create MySQL Tables $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); } 11/23/2018 3-PHP-CONNECT-TO-MySQL 8
  • 9. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Notes on the table above • NOT NULL - Each row must contain a value for that column, null values are not allowed • DEFAULT value - Set a default value that is added when no other value is passed • UNSIGNED - Used for number types, limits the stored data to positive numbers and zero • AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each time a new record is added • PRIMARY KEY - Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting is often an ID number, and is often used with AUTO_INCREMENT 11/23/2018 3-PHP-CONNECT-TO-MySQL 9
  • 10. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Insert Data Into MySQL After a database and a table have been created, we can start adding data in them. • Here are some syntax rules to follow: • The SQL query must be quoted in PHP • String values inside the SQL query must be quoted • Numeric values must not be quoted • The word NULL must not be quoted Note: I f a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP (like the "reg_date" column), it is no need to be specified in the SQL query; MySQL will automatically add the value. 11/23/2018 3-PHP-CONNECT-TO-MySQL 10
  • 11. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Insert Data Into MySQL $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if (mysqli_query($conn, $sql)) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } 11/23/2018 3-PHP-CONNECT-TO-MySQL 11
  • 12. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Insert Multiple Records Into MySQL $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); } 11/23/2018 3-PHP-CONNECT-TO-MySQL 12
  • 13. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Select Data From a MySQL $sql = "SELECT * FROM MyGuests"; //$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)) { //var_dump($row); echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; } } else { echo "0 results"; } 11/23/2018 3-PHP-CONNECT-TO-MySQL 13
  • 14. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Delete Data From a MySQL $sql = "DELETE FROM MyGuests WHERE id=3"; if (mysqli_query($conn, $sql)) { echo "Record deleted successfully"; } else { echo "Error deleting record: " . mysqli_error($conn); } 11/23/2018 3-PHP-CONNECT-TO-MySQL 14
  • 15. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Update Data In a MySQL $sql = "UPDATE MyGuests SET lastname='Mugund' WHERE id=9"; if (mysqli_query($conn, $sql)) { echo "Record updated successfully"; } else { echo "Error updating record: " . mysqli_error($conn); } 11/23/2018 3-PHP-CONNECT-TO-MySQL 15
  • 16. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Limit Data Selections From a MySQL $sql = "SELECT * FROM MyGuests ORDER BY id ASC LIMIT 10 OFFSET 15"; //$sql = "SELECT * FROM MyGuests ORDER BY id ASC LIMIT 10 OFFSET 10"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; } } else { echo "0 results"; } Note: The SQL query above says "return only 10 records, start on record 16 (OFFSET 15)": 11/23/2018 3-PHP-CONNECT-TO-MySQL 16
  • 17. Sri Lanka-German Training InstituteDepartment of Information and Communication Technology Reference www.w3schools.com www.php.net www.slgti.com Friday, November 23, 2018 17