SlideShare a Scribd company logo
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$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;
}
$conn->close();
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
MULTIPLE RECORDS INSERTED
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$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 ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// begin the transaction
$conn->beginTransaction();
// our SQL statememtns
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')");
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', 'mary@example.com')");
$conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', 'julie@example.com')");
// commit the transaction
$conn->commit();
echo "New records created successfully";
}
catch(PDOException $e)
{
// roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
Prepared statements are very useful against SQL injections.
Prepared Statements and Bound Parameters
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with
high efficiency.
Prepared statements basically work like this:
1. Prepare: An SQL statement template is created and sent to the database. Certain values are left
unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?,
?)
2. The database parses, compiles, and performs query optimization on the SQL statement template,
and stores the result without executing it
3. Execute: At a later time, the application binds the values to the parameters, and the database
executes the statement. The application may execute the statement as many times as it wants
with different values
Compared to executing SQL statements directly, prepared statements have two main advantages:
• Prepared statements reduces parsing time as the preparation on the query is done only once
(although the statement is executed multiple times)
• Bound parameters minimize bandwidth to the server as you need send only the parameters each
time, and not the whole query
• Prepared statements are very useful against SQL injections, because parameter values, which
are transmitted later using a different protocol, need not be correctly escaped. If the original
statement template is not derived from external input, SQL injection cannot occur.
Prepared Statements in MySQLi
The following example uses prepared statements and bound parameters in MySQLi:
Example (MySQLi with Prepared Statements)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);
// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
Code lines to explain from the example above:
"INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"
In our SQL, we insert a question mark (?) where we want to substitute in an integer, string, double or
blob value.
Then, have a look at the bind_param() function:
$stmt->bind_param("sss", $firstname, $lastname, $email);
This function binds the parameters to the SQL query and tells the database what the parameters are.
The "sss" argument lists the types of data that the parameters are. The s character tells mysql that the
parameter is a string.
The argument may be one of four types:
• i - integer
• d - double
• s - string
• b - BLOB
We must have one of these for each parameter.
By telling mysql what type of data to expect, we minimize the risk of SQL injections.
Note: If we want to insert any data from external sources (like user input), it is very important
that the data is sanitized and validated.
Prepared Statements in PDO
The following example uses prepared statements and bound parameters in PDO:
Example (PDO with Prepared Statements)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email)
VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();
// insert another row
$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();
// insert another row
$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>

More Related Content

What's hot

Using web2py's DAL in other projects or frameworks
Using web2py's DAL in other projects or frameworksUsing web2py's DAL in other projects or frameworks
Using web2py's DAL in other projects or frameworks
Bruno Rocha
 
PHP and Mysql
PHP and MysqlPHP and Mysql
PHP and Mysql
Sankhadeep Roy
 
Database presentation
Database presentationDatabase presentation
Database presentation
webhostingguy
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
markstory
 
Php 101: PDO
Php 101: PDOPhp 101: PDO
Php 101: PDO
Jeremy Kendall
 
Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
José Lorenzo Rodríguez Urdaneta
 
Web2py
Web2pyWeb2py
Web2py
Lucas D
 
Introduction to php database connectivity
Introduction to php  database connectivityIntroduction to php  database connectivity
Introduction to php database connectivity
baabtra.com - No. 1 supplier of quality freshers
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
Wez Furlong
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
Valentine Dianov
 
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
Firdaus Adib
 
Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
José Lorenzo Rodríguez Urdaneta
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3
markstory
 
Idoc script beginner guide
Idoc script beginner guide Idoc script beginner guide
Idoc script beginner guide
Vinay Kumar
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
Taha Malampatti
 
Web 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHPWeb 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHP
Mohammad Imam Hossain
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
G Woo
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
Wim Godden
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
salissal
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
Pierre MARTIN
 

What's hot (20)

Using web2py's DAL in other projects or frameworks
Using web2py's DAL in other projects or frameworksUsing web2py's DAL in other projects or frameworks
Using web2py's DAL in other projects or frameworks
 
PHP and Mysql
PHP and MysqlPHP and Mysql
PHP and Mysql
 
Database presentation
Database presentationDatabase presentation
Database presentation
 
Future of HTTP in CakePHP
Future of HTTP in CakePHPFuture of HTTP in CakePHP
Future of HTTP in CakePHP
 
Php 101: PDO
Php 101: PDOPhp 101: PDO
Php 101: PDO
 
Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
 
Web2py
Web2pyWeb2py
Web2py
 
Introduction to php database connectivity
Introduction to php  database connectivityIntroduction to php  database connectivity
Introduction to php database connectivity
 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
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
 
Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
 
New in cakephp3
New in cakephp3New in cakephp3
New in cakephp3
 
Idoc script beginner guide
Idoc script beginner guide Idoc script beginner guide
Idoc script beginner guide
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Web 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHPWeb 11 | AJAX + JSON + PHP
Web 11 | AJAX + JSON + PHP
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
Using php with my sql
Using php with my sqlUsing php with my sql
Using php with my sql
 
Internationalizing CakePHP Applications
Internationalizing CakePHP ApplicationsInternationalizing CakePHP Applications
Internationalizing CakePHP Applications
 

Viewers also liked

Godrej LOUD 2015
Godrej LOUD 2015 Godrej LOUD 2015
Godrej LOUD 2015
Kritika Agarwal
 
Tarea
TareaTarea
Tarea
Fiopi Hp
 
Unidad 10
Unidad 10Unidad 10
Unidad 10
312alexjunior
 
Hey, hayley test shots
Hey, hayley test shotsHey, hayley test shots
Hey, hayley test shots
HollyFairbairn
 
Unidad 11
Unidad 11Unidad 11
Unidad 11
315moises
 
ORGANOS DE GOBIERNO DE LA UNIVERSIDAD DE LA GUAJIRA
ORGANOS DE GOBIERNO DE LA UNIVERSIDAD DE LA GUAJIRAORGANOS DE GOBIERNO DE LA UNIVERSIDAD DE LA GUAJIRA
ORGANOS DE GOBIERNO DE LA UNIVERSIDAD DE LA GUAJIRA
jennifer1207
 
Pto. pobreza en los estados fronterizos del norte 111
Pto. pobreza en los estados fronterizos del  norte 111Pto. pobreza en los estados fronterizos del  norte 111
Pto. pobreza en los estados fronterizos del norte 111
UNAM
 
Filming schedule
Filming scheduleFilming schedule
Filming schedule
Agnesa01
 
Laboratorio de sociales De Maestria
Laboratorio de sociales De MaestriaLaboratorio de sociales De Maestria
Laboratorio de sociales De Maestria
ikkisv
 
Герої не вмирають...
Герої  не  вмирають...Герої  не  вмирають...
Герої не вмирають...
baidaruslan
 
20151011 食品貿易講座
20151011 食品貿易講座20151011 食品貿易講座
20151011 食品貿易講座
Pond Jeng
 
HMC2013
HMC2013HMC2013
HMC2013
David Rowden
 
Strategic marketing plan for slt megaline for the year 2015
Strategic marketing plan for slt megaline for the year 2015Strategic marketing plan for slt megaline for the year 2015
Strategic marketing plan for slt megaline for the year 2015
Royal Ceramics Lanka PLC
 
Tecnologia arias diapositivas
Tecnologia arias diapositivasTecnologia arias diapositivas
Tecnologia arias diapositivas
mafelu100
 

Viewers also liked (14)

Godrej LOUD 2015
Godrej LOUD 2015 Godrej LOUD 2015
Godrej LOUD 2015
 
Tarea
TareaTarea
Tarea
 
Unidad 10
Unidad 10Unidad 10
Unidad 10
 
Hey, hayley test shots
Hey, hayley test shotsHey, hayley test shots
Hey, hayley test shots
 
Unidad 11
Unidad 11Unidad 11
Unidad 11
 
ORGANOS DE GOBIERNO DE LA UNIVERSIDAD DE LA GUAJIRA
ORGANOS DE GOBIERNO DE LA UNIVERSIDAD DE LA GUAJIRAORGANOS DE GOBIERNO DE LA UNIVERSIDAD DE LA GUAJIRA
ORGANOS DE GOBIERNO DE LA UNIVERSIDAD DE LA GUAJIRA
 
Pto. pobreza en los estados fronterizos del norte 111
Pto. pobreza en los estados fronterizos del  norte 111Pto. pobreza en los estados fronterizos del  norte 111
Pto. pobreza en los estados fronterizos del norte 111
 
Filming schedule
Filming scheduleFilming schedule
Filming schedule
 
Laboratorio de sociales De Maestria
Laboratorio de sociales De MaestriaLaboratorio de sociales De Maestria
Laboratorio de sociales De Maestria
 
Герої не вмирають...
Герої  не  вмирають...Герої  не  вмирають...
Герої не вмирають...
 
20151011 食品貿易講座
20151011 食品貿易講座20151011 食品貿易講座
20151011 食品貿易講座
 
HMC2013
HMC2013HMC2013
HMC2013
 
Strategic marketing plan for slt megaline for the year 2015
Strategic marketing plan for slt megaline for the year 2015Strategic marketing plan for slt megaline for the year 2015
Strategic marketing plan for slt megaline for the year 2015
 
Tecnologia arias diapositivas
Tecnologia arias diapositivasTecnologia arias diapositivas
Tecnologia arias diapositivas
 

Similar to Stored Procedure

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
Arti Parab Academics
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
Rasan Samarasinghe
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxPHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptx
CynthiaKendi1
 
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
Dhivyaa C.R
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
DrDhivyaaCRAssistant
 
4.3 MySQL + PHP
4.3 MySQL + PHP4.3 MySQL + PHP
4.3 MySQL + PHP
Jalpesh Vasa
 
Php summary
Php summaryPhp summary
Php summary
Michelle Darling
 
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
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
ADARSH BHATT
 
Pemrograman Web 8 - MySQL
Pemrograman Web 8 - MySQLPemrograman Web 8 - MySQL
Pemrograman Web 8 - MySQL
Nur Fadli Utomo
 
MySQLi
MySQLiMySQLi
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
okelloerick
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele
 
How to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdfHow to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdf
Appweb Coders
 
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
saritasingh19866
 
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
Dave Stokes
 
Php Security By Mugdha And Anish
Php Security By Mugdha And AnishPhp Security By Mugdha And Anish
Php Security By Mugdha And Anish
OSSCube
 
Php Data Objects
Php Data ObjectsPhp Data Objects
Php Data Objects
hiren.joshi
 
Mongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg Solutions
Metatagg Solutions
 
Database Management - Lecture 4 - PHP and Mysql
Database Management - Lecture 4 - PHP and MysqlDatabase Management - Lecture 4 - PHP and Mysql
Database Management - Lecture 4 - PHP and Mysql
Al-Mamun Sarkar
 

Similar to Stored Procedure (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
 
PHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.pptxPHP DATABASE MANAGEMENT.pptx
PHP DATABASE MANAGEMENT.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
 
UNIT V (5).pptx
UNIT V (5).pptxUNIT V (5).pptx
UNIT V (5).pptx
 
4.3 MySQL + PHP
4.3 MySQL + PHP4.3 MySQL + PHP
4.3 MySQL + PHP
 
Php summary
Php summaryPhp summary
Php summary
 
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
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
Pemrograman Web 8 - MySQL
Pemrograman Web 8 - MySQLPemrograman Web 8 - MySQL
Pemrograman Web 8 - MySQL
 
MySQLi
MySQLiMySQLi
MySQLi
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
How to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdfHow to Create Login and Registration API in PHP.pdf
How to Create Login and Registration API in PHP.pdf
 
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
 
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
 
Php Security By Mugdha And Anish
Php Security By Mugdha And AnishPhp Security By Mugdha And Anish
Php Security By Mugdha And Anish
 
Php Data Objects
Php Data ObjectsPhp Data Objects
Php Data Objects
 
Mongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg SolutionsMongo Presentation by Metatagg Solutions
Mongo Presentation by Metatagg Solutions
 
Database Management - Lecture 4 - PHP and Mysql
Database Management - Lecture 4 - PHP and MysqlDatabase Management - Lecture 4 - PHP and Mysql
Database Management - Lecture 4 - PHP and Mysql
 

Recently uploaded

Experts live - Improving user adoption with AI
Experts live - Improving user adoption with AIExperts live - Improving user adoption with AI
Experts live - Improving user adoption with AI
jitskeb
 
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
v7oacc3l
 
State of Artificial intelligence Report 2023
State of Artificial intelligence Report 2023State of Artificial intelligence Report 2023
State of Artificial intelligence Report 2023
kuntobimo2016
 
一比一原版(爱大毕业证书)爱丁堡大学毕业证如何办理
一比一原版(爱大毕业证书)爱丁堡大学毕业证如何办理一比一原版(爱大毕业证书)爱丁堡大学毕业证如何办理
一比一原版(爱大毕业证书)爱丁堡大学毕业证如何办理
g4dpvqap0
 
Analysis insight about a Flyball dog competition team's performance
Analysis insight about a Flyball dog competition team's performanceAnalysis insight about a Flyball dog competition team's performance
Analysis insight about a Flyball dog competition team's performance
roli9797
 
一比一原版(Coventry毕业证书)考文垂大学毕业证如何办理
一比一原版(Coventry毕业证书)考文垂大学毕业证如何办理一比一原版(Coventry毕业证书)考文垂大学毕业证如何办理
一比一原版(Coventry毕业证书)考文垂大学毕业证如何办理
74nqk8xf
 
一比一原版(Harvard毕业证书)哈佛大学毕业证如何办理
一比一原版(Harvard毕业证书)哈佛大学毕业证如何办理一比一原版(Harvard毕业证书)哈佛大学毕业证如何办理
一比一原版(Harvard毕业证书)哈佛大学毕业证如何办理
zsjl4mimo
 
The Ipsos - AI - Monitor 2024 Report.pdf
The  Ipsos - AI - Monitor 2024 Report.pdfThe  Ipsos - AI - Monitor 2024 Report.pdf
The Ipsos - AI - Monitor 2024 Report.pdf
Social Samosa
 
一比一原版(牛布毕业证书)牛津布鲁克斯大学毕业证如何办理
一比一原版(牛布毕业证书)牛津布鲁克斯大学毕业证如何办理一比一原版(牛布毕业证书)牛津布鲁克斯大学毕业证如何办理
一比一原版(牛布毕业证书)牛津布鲁克斯大学毕业证如何办理
74nqk8xf
 
06-04-2024 - NYC Tech Week - Discussion on Vector Databases, Unstructured Dat...
06-04-2024 - NYC Tech Week - Discussion on Vector Databases, Unstructured Dat...06-04-2024 - NYC Tech Week - Discussion on Vector Databases, Unstructured Dat...
06-04-2024 - NYC Tech Week - Discussion on Vector Databases, Unstructured Dat...
Timothy Spann
 
一比一原版(Chester毕业证书)切斯特大学毕业证如何办理
一比一原版(Chester毕业证书)切斯特大学毕业证如何办理一比一原版(Chester毕业证书)切斯特大学毕业证如何办理
一比一原版(Chester毕业证书)切斯特大学毕业证如何办理
74nqk8xf
 
Learn SQL from basic queries to Advance queries
Learn SQL from basic queries to Advance queriesLearn SQL from basic queries to Advance queries
Learn SQL from basic queries to Advance queries
manishkhaire30
 
一比一原版(UMN文凭证书)明尼苏达大学毕业证如何办理
一比一原版(UMN文凭证书)明尼苏达大学毕业证如何办理一比一原版(UMN文凭证书)明尼苏达大学毕业证如何办理
一比一原版(UMN文凭证书)明尼苏达大学毕业证如何办理
nyfuhyz
 
The Building Blocks of QuestDB, a Time Series Database
The Building Blocks of QuestDB, a Time Series DatabaseThe Building Blocks of QuestDB, a Time Series Database
The Building Blocks of QuestDB, a Time Series Database
javier ramirez
 
Influence of Marketing Strategy and Market Competition on Business Plan
Influence of Marketing Strategy and Market Competition on Business PlanInfluence of Marketing Strategy and Market Competition on Business Plan
Influence of Marketing Strategy and Market Competition on Business Plan
jerlynmaetalle
 
Udemy_2024_Global_Learning_Skills_Trends_Report (1).pdf
Udemy_2024_Global_Learning_Skills_Trends_Report (1).pdfUdemy_2024_Global_Learning_Skills_Trends_Report (1).pdf
Udemy_2024_Global_Learning_Skills_Trends_Report (1).pdf
Fernanda Palhano
 
Global Situational Awareness of A.I. and where its headed
Global Situational Awareness of A.I. and where its headedGlobal Situational Awareness of A.I. and where its headed
Global Situational Awareness of A.I. and where its headed
vikram sood
 
STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...
STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...
STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...
sameer shah
 
Beyond the Basics of A/B Tests: Highly Innovative Experimentation Tactics You...
Beyond the Basics of A/B Tests: Highly Innovative Experimentation Tactics You...Beyond the Basics of A/B Tests: Highly Innovative Experimentation Tactics You...
Beyond the Basics of A/B Tests: Highly Innovative Experimentation Tactics You...
Aggregage
 
4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...
4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...
4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...
Social Samosa
 

Recently uploaded (20)

Experts live - Improving user adoption with AI
Experts live - Improving user adoption with AIExperts live - Improving user adoption with AI
Experts live - Improving user adoption with AI
 
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
在线办理(英国UCA毕业证书)创意艺术大学毕业证在读证明一模一样
 
State of Artificial intelligence Report 2023
State of Artificial intelligence Report 2023State of Artificial intelligence Report 2023
State of Artificial intelligence Report 2023
 
一比一原版(爱大毕业证书)爱丁堡大学毕业证如何办理
一比一原版(爱大毕业证书)爱丁堡大学毕业证如何办理一比一原版(爱大毕业证书)爱丁堡大学毕业证如何办理
一比一原版(爱大毕业证书)爱丁堡大学毕业证如何办理
 
Analysis insight about a Flyball dog competition team's performance
Analysis insight about a Flyball dog competition team's performanceAnalysis insight about a Flyball dog competition team's performance
Analysis insight about a Flyball dog competition team's performance
 
一比一原版(Coventry毕业证书)考文垂大学毕业证如何办理
一比一原版(Coventry毕业证书)考文垂大学毕业证如何办理一比一原版(Coventry毕业证书)考文垂大学毕业证如何办理
一比一原版(Coventry毕业证书)考文垂大学毕业证如何办理
 
一比一原版(Harvard毕业证书)哈佛大学毕业证如何办理
一比一原版(Harvard毕业证书)哈佛大学毕业证如何办理一比一原版(Harvard毕业证书)哈佛大学毕业证如何办理
一比一原版(Harvard毕业证书)哈佛大学毕业证如何办理
 
The Ipsos - AI - Monitor 2024 Report.pdf
The  Ipsos - AI - Monitor 2024 Report.pdfThe  Ipsos - AI - Monitor 2024 Report.pdf
The Ipsos - AI - Monitor 2024 Report.pdf
 
一比一原版(牛布毕业证书)牛津布鲁克斯大学毕业证如何办理
一比一原版(牛布毕业证书)牛津布鲁克斯大学毕业证如何办理一比一原版(牛布毕业证书)牛津布鲁克斯大学毕业证如何办理
一比一原版(牛布毕业证书)牛津布鲁克斯大学毕业证如何办理
 
06-04-2024 - NYC Tech Week - Discussion on Vector Databases, Unstructured Dat...
06-04-2024 - NYC Tech Week - Discussion on Vector Databases, Unstructured Dat...06-04-2024 - NYC Tech Week - Discussion on Vector Databases, Unstructured Dat...
06-04-2024 - NYC Tech Week - Discussion on Vector Databases, Unstructured Dat...
 
一比一原版(Chester毕业证书)切斯特大学毕业证如何办理
一比一原版(Chester毕业证书)切斯特大学毕业证如何办理一比一原版(Chester毕业证书)切斯特大学毕业证如何办理
一比一原版(Chester毕业证书)切斯特大学毕业证如何办理
 
Learn SQL from basic queries to Advance queries
Learn SQL from basic queries to Advance queriesLearn SQL from basic queries to Advance queries
Learn SQL from basic queries to Advance queries
 
一比一原版(UMN文凭证书)明尼苏达大学毕业证如何办理
一比一原版(UMN文凭证书)明尼苏达大学毕业证如何办理一比一原版(UMN文凭证书)明尼苏达大学毕业证如何办理
一比一原版(UMN文凭证书)明尼苏达大学毕业证如何办理
 
The Building Blocks of QuestDB, a Time Series Database
The Building Blocks of QuestDB, a Time Series DatabaseThe Building Blocks of QuestDB, a Time Series Database
The Building Blocks of QuestDB, a Time Series Database
 
Influence of Marketing Strategy and Market Competition on Business Plan
Influence of Marketing Strategy and Market Competition on Business PlanInfluence of Marketing Strategy and Market Competition on Business Plan
Influence of Marketing Strategy and Market Competition on Business Plan
 
Udemy_2024_Global_Learning_Skills_Trends_Report (1).pdf
Udemy_2024_Global_Learning_Skills_Trends_Report (1).pdfUdemy_2024_Global_Learning_Skills_Trends_Report (1).pdf
Udemy_2024_Global_Learning_Skills_Trends_Report (1).pdf
 
Global Situational Awareness of A.I. and where its headed
Global Situational Awareness of A.I. and where its headedGlobal Situational Awareness of A.I. and where its headed
Global Situational Awareness of A.I. and where its headed
 
STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...
STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...
STATATHON: Unleashing the Power of Statistics in a 48-Hour Knowledge Extravag...
 
Beyond the Basics of A/B Tests: Highly Innovative Experimentation Tactics You...
Beyond the Basics of A/B Tests: Highly Innovative Experimentation Tactics You...Beyond the Basics of A/B Tests: Highly Innovative Experimentation Tactics You...
Beyond the Basics of A/B Tests: Highly Innovative Experimentation Tactics You...
 
4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...
4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...
4th Modern Marketing Reckoner by MMA Global India & Group M: 60+ experts on W...
 

Stored Procedure

  • 1. <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $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; } $conn->close(); ?> Example (PDO) <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; // use exec() because no results are returned $conn->exec($sql); echo "New record created successfully"; }
  • 2. catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?> <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if ($conn->query($sql) === TRUE) { $last_id = $conn->insert_id; echo "New record created successfully. Last inserted ID is: " . $last_id; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?> <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; // use exec() because no results are returned
  • 3. $conn->exec($sql); $last_id = $conn->lastInsertId(); echo "New record created successfully. Last inserted ID is: " . $last_id; } catch(PDOException $e) { echo $sql . "<br>" . $e->getMessage(); } $conn = null; ?> MULTIPLE RECORDS INSERTED <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $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 ($conn->multi_query($sql) === TRUE) { echo "New records created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?> <?php $servername = "localhost"; $username = "username"; $password = "password";
  • 4. $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // begin the transaction $conn->beginTransaction(); // our SQL statememtns $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"); $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com')"); $conn->exec("INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"); // commit the transaction $conn->commit(); echo "New records created successfully"; } catch(PDOException $e) { // roll back the transaction if something failed $conn->rollback(); echo "Error: " . $e->getMessage(); } $conn = null; ?> Prepared statements are very useful against SQL injections. Prepared Statements and Bound Parameters A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency. Prepared statements basically work like this: 1. Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?)
  • 5. 2. The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it 3. Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values Compared to executing SQL statements directly, prepared statements have two main advantages: • Prepared statements reduces parsing time as the preparation on the query is done only once (although the statement is executed multiple times) • Bound parameters minimize bandwidth to the server as you need send only the parameters each time, and not the whole query • Prepared statements are very useful against SQL injections, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur. Prepared Statements in MySQLi The following example uses prepared statements and bound parameters in MySQLi: Example (MySQLi with Prepared Statements) <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // prepare and bind $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)"); $stmt->bind_param("sss", $firstname, $lastname, $email); // set parameters and execute $firstname = "John";
  • 6. $lastname = "Doe"; $email = "john@example.com"; $stmt->execute(); $firstname = "Mary"; $lastname = "Moe"; $email = "mary@example.com"; $stmt->execute(); $firstname = "Julie"; $lastname = "Dooley"; $email = "julie@example.com"; $stmt->execute(); echo "New records created successfully"; $stmt->close(); $conn->close(); ?> Code lines to explain from the example above: "INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)" In our SQL, we insert a question mark (?) where we want to substitute in an integer, string, double or blob value. Then, have a look at the bind_param() function: $stmt->bind_param("sss", $firstname, $lastname, $email); This function binds the parameters to the SQL query and tells the database what the parameters are. The "sss" argument lists the types of data that the parameters are. The s character tells mysql that the parameter is a string. The argument may be one of four types: • i - integer • d - double • s - string • b - BLOB We must have one of these for each parameter. By telling mysql what type of data to expect, we minimize the risk of SQL injections.
  • 7. Note: If we want to insert any data from external sources (like user input), it is very important that the data is sanitized and validated. Prepared Statements in PDO The following example uses prepared statements and bound parameters in PDO: Example (PDO with Prepared Statements) <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDBPDO"; try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // prepare sql and bind parameters $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (:firstname, :lastname, :email)"); $stmt->bindParam(':firstname', $firstname); $stmt->bindParam(':lastname', $lastname); $stmt->bindParam(':email', $email); // insert a row $firstname = "John"; $lastname = "Doe"; $email = "john@example.com"; $stmt->execute(); // insert another row $firstname = "Mary"; $lastname = "Moe"; $email = "mary@example.com"; $stmt->execute(); // insert another row $firstname = "Julie";
  • 8. $lastname = "Dooley"; $email = "julie@example.com"; $stmt->execute(); echo "New records created successfully"; } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } $conn = null; ?>