SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Similaire à 3 php-connect-to-my sql

Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
salissal
 
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
moirarandell
 

Similaire à 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
 

Plus de Achchuthan Yogarajah

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
Achchuthan Yogarajah
 

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

Dernier

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
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
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Dernier (20)

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
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
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
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
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 

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