SlideShare a Scribd company logo
PHP
(Session 2)
INFO 257 Supplement
Outline
• PHP Classes (Brief Overview)
• Accessing MySQL via the mysqli class
Classes and OOP
(Basic Conceptual Overview)
Class Definition
(Blueprint)
class dog{
//properties
//methods
}
Define the blueprint of
your own class (object)
Instantiate instances of your object
and use them in your program
$ben = new dog;
$sunny = new dog;
$sugar = new dog;
Defining Classes
class dog {
//Properties
public $name;
public $breed;
//Methods
public function bark(){
echo $this->name . “ barked… Woof!”;
}
//Constructor (optional)
public __construct($nameOfDog){
$this->name = $nameOfDog;
}
}
Working with Classes
$sugar = new dog(“Sugar”); //pass “Sugar” to constructor
$sugar->breed = “German Shepherd”; //set breed property
equal to “German Shepherd”
echo $sugar->name . “ is a “ . $sugar->breed;
>>Sugar is a German Shepherd
$sugar->bark(); //call the “bark” method
>>sugar barked… Woof!
Mysqli Class
The mysqli class is the main class you can use to:
• Set up a connection to the MySQL database
• Send SQL queries to the MySQL database
(CRUD Operations)
• Read results (if any) from the query
• Check for any error connecting to or executing
SQL queries on a MySQL database
Connecting to DB with Mysqli
//Instantiate mysqli object & create connection
$db = new mysqli(“localhost”, “username”,
“password”, “database_name”);
//Check for any errors connecting
If($db->connect_errorno){
//There was an error connecting to the database. Put code here on
what you would like to about it like…
echo “Error: ” . $db->connect_error;
}
Querying the DB via Mysqli (Single Query)
//Construct some query (it’s just a string)
$query_noresult = “INSERT INTO …”;
$query_result = ‘’SELECT * FROM DIVECUST”;
2 Types of Queries
PHP MySQL
No Result Queries
INSERT, DELETE, CREATE, etc…
PHP MySQL
Result Queries
SELECT
No Result Queries
If($db->query($query_noresult) === TRUE){
//Your query worked, yay
}
Note about INSERT SQL queries
• You can use $db->insert_id; to retrieve the
AUTO_INCREMENT ID generated for an inserted
record. You do NOT need to run a separate query
to get that ID value.
Result Queries
if($result = $db->query($query_result)){
echo $result->num_rows;
while($row = $result->fetch-array()){
echo $row[0] . “ ” . $row[‘Name’];
}
$result->free();
}
Returns a
mysqli_result object
Column or Attribute name
returned from query
Free up the result
from memory
Result Modes
You can return results in 2 ways (result modes)
$db->query($query_result, MYSQLI_STORE_RESULT)
• Return entire results to memory
• Can use $result->data_seek(index) to jump to different rows in your result
set (i.e. after you loop through the results, do $result->data_seek(0); to go
to starting point to loop again)
• Default (this is the executed mode if you don’t specify a “result mode”)
$db->query($query_result, MYSQLI_USE_RESULT)
• MySQL “spoon feeds” the rows to server running PHP each time a fetches
a row
• Useful if expecting a large dataset (too large to put in memory of PHP
server)
• Must free results in order to run another query ($result->free();)
Closing Connections
When you are done using the database, make
sure to close the connection…
$db->close();
Demo Time
DEMO
Team
team_id
name
mascot
color
Player
player_id
fname
lname
pic
TeamPlayer
team_id
player_id
localhost/sports/teams.php
Passing Variables to PHP (POST)
<form method=“post” action=“process.php”>
<input type=“text” name=“fname”/>
<input type=“text” name=“lname” />
<input type=“submit” value=“Submit”/>
</form>
HTTP POST Request to process.php
fname=Arian
lname=Shams
<?php
$var1 = $_POST[‘fname’];
$var2 = $_POST[‘lname’];
?>
Your form html or php file The process.php file that will
process the request (which could be
the same as the posting file)
Passing Variable to PHP (GET)
www.site.com/index.php?query=ischool&lang=en
Start of query string key=value pairs Separator
Note- certain characters cannot be put in the URL (such as space
character). You will to “URL Encode” those special characters. For example,
a space character will show up as a %20 in the URL query string.
<?php
$var1 = $_GET[‘query’];
$var2 = $_GET[‘lang’];
?>
Security (SQL Injection and XSS)
HTTP POST Request
fname=Arian
lname=SQL Code
In your PHP…
$query = “INSERT INTO table (fname, lname)”;
$query .= “VALUES (‘{$_POST[‘fname’]}’, ‘{$_POST[‘lname’]}’);”
A malicious user can submit (POST or GET)
• SQL Code  SQL Injection Attack, or
• HTML tags that could be anything from a
form to a <script> tag  XSS Attack.
Preventing SQL Injection & XSS
To prevent this, you have to sanitize your input
variables and make sure you output safe HTML
//Sanitize  SQL Injection
$sanitized_variable = $db->real_escape_string($_POST[‘lname’]);
//Output Safe HTML  XSS
echo htmlspecialchars($row[‘lname’]);
You can try to sanitize for HTML tags by using strip_tags($_POST[])
before you input the value into the database. Just make sure that is what
you want to do…
Additional Security Tip
Don’t type out the username and password
when instantiating mysqli. Instead, create a
special PHP file that defines certain constants
outside the root of your website which you can
then include and use in your PHP code.
define(SQL_PASSWORD, “mypassword”);
Demo Time
DEMO
Constant Definitions constants.php
Use of $_GET localhost/sports/team.php?id=1
Regular Posting localhost/sports/players.php
Use of $_POST and INSERT localhost/sports/addPlayer-process.php
Multiselect/Array Posting localhost/sports/editRoster.php?id=1
Use of $_POST arrays localhost/sports/editRoster-process.php
Deleting localhost/sports/deletePlayer-process.php?id=1
Additional Notes about POSTing
• If a checkbox input is not checked, that variable
will NOT be passed in the POST (or GET)
– Use isset() to see if a variable exists: isset($_POST[]);
• POSTing an array of variables to PHP (such as a
multiselect) requires you to append brackets to
the name of the input type.
<select multiple=“multiple” name=“mylist[]”>…
Next Time
You Choose the Topic!
Email me with PHP and/or database topics you would
like to review and I will select the questions that seems
like it would benefit the class the most. I will take the
first 15 minutes to review the first two sessions but
then after that the floor is open to the topics you
choose.

More Related Content

Similar to php2.pptx

Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2ADARSH BHATT
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
Nishan Subedi
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
Azim Kurt
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
Barang CK
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
Viswanath Polaki
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
Michelangelo van Dam
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
Michelangelo van Dam
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
Nate Abele
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectJonathan Wage
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
Nate Abele
 
[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
Adam Tomat
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
Michelangelo van Dam
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
ddiers
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
Michelangelo van Dam
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
Basuke Suzuki
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
Daniel Knell
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo Web
Mikel Torres Ugarte
 
Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemAzharul Haque Shohan
 

Similar to php2.pptx (20)

Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
Drupal 8 database api
Drupal 8 database apiDrupal 8 database api
Drupal 8 database api
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo Web
 
Creating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login SystemCreating a Simple PHP and MySQL-Based Login System
Creating a Simple PHP and MySQL-Based Login System
 

Recently uploaded

block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
Jayaprasanna4
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
Kamal Acharya
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
R&R Consult
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
abh.arya
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
LIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptLIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.ppt
ssuser9bd3ba
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
Kamal Acharya
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
ankuprajapati0525
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 

Recently uploaded (20)

block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
ethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.pptethical hacking-mobile hacking methods.ppt
ethical hacking-mobile hacking methods.ppt
 
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdfCOLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
COLLEGE BUS MANAGEMENT SYSTEM PROJECT REPORT.pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
Democratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek AryaDemocratizing Fuzzing at Scale by Abhishek Arya
Democratizing Fuzzing at Scale by Abhishek Arya
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
LIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.pptLIGA(E)11111111111111111111111111111111111111111.ppt
LIGA(E)11111111111111111111111111111111111111111.ppt
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
The role of big data in decision making.
The role of big data in decision making.The role of big data in decision making.
The role of big data in decision making.
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 

php2.pptx

  • 2. Outline • PHP Classes (Brief Overview) • Accessing MySQL via the mysqli class
  • 3. Classes and OOP (Basic Conceptual Overview) Class Definition (Blueprint) class dog{ //properties //methods } Define the blueprint of your own class (object) Instantiate instances of your object and use them in your program $ben = new dog; $sunny = new dog; $sugar = new dog;
  • 4. Defining Classes class dog { //Properties public $name; public $breed; //Methods public function bark(){ echo $this->name . “ barked… Woof!”; } //Constructor (optional) public __construct($nameOfDog){ $this->name = $nameOfDog; } }
  • 5. Working with Classes $sugar = new dog(“Sugar”); //pass “Sugar” to constructor $sugar->breed = “German Shepherd”; //set breed property equal to “German Shepherd” echo $sugar->name . “ is a “ . $sugar->breed; >>Sugar is a German Shepherd $sugar->bark(); //call the “bark” method >>sugar barked… Woof!
  • 6. Mysqli Class The mysqli class is the main class you can use to: • Set up a connection to the MySQL database • Send SQL queries to the MySQL database (CRUD Operations) • Read results (if any) from the query • Check for any error connecting to or executing SQL queries on a MySQL database
  • 7. Connecting to DB with Mysqli //Instantiate mysqli object & create connection $db = new mysqli(“localhost”, “username”, “password”, “database_name”); //Check for any errors connecting If($db->connect_errorno){ //There was an error connecting to the database. Put code here on what you would like to about it like… echo “Error: ” . $db->connect_error; }
  • 8. Querying the DB via Mysqli (Single Query) //Construct some query (it’s just a string) $query_noresult = “INSERT INTO …”; $query_result = ‘’SELECT * FROM DIVECUST”; 2 Types of Queries PHP MySQL No Result Queries INSERT, DELETE, CREATE, etc… PHP MySQL Result Queries SELECT
  • 9. No Result Queries If($db->query($query_noresult) === TRUE){ //Your query worked, yay } Note about INSERT SQL queries • You can use $db->insert_id; to retrieve the AUTO_INCREMENT ID generated for an inserted record. You do NOT need to run a separate query to get that ID value.
  • 10. Result Queries if($result = $db->query($query_result)){ echo $result->num_rows; while($row = $result->fetch-array()){ echo $row[0] . “ ” . $row[‘Name’]; } $result->free(); } Returns a mysqli_result object Column or Attribute name returned from query Free up the result from memory
  • 11. Result Modes You can return results in 2 ways (result modes) $db->query($query_result, MYSQLI_STORE_RESULT) • Return entire results to memory • Can use $result->data_seek(index) to jump to different rows in your result set (i.e. after you loop through the results, do $result->data_seek(0); to go to starting point to loop again) • Default (this is the executed mode if you don’t specify a “result mode”) $db->query($query_result, MYSQLI_USE_RESULT) • MySQL “spoon feeds” the rows to server running PHP each time a fetches a row • Useful if expecting a large dataset (too large to put in memory of PHP server) • Must free results in order to run another query ($result->free();)
  • 12. Closing Connections When you are done using the database, make sure to close the connection… $db->close();
  • 14. Passing Variables to PHP (POST) <form method=“post” action=“process.php”> <input type=“text” name=“fname”/> <input type=“text” name=“lname” /> <input type=“submit” value=“Submit”/> </form> HTTP POST Request to process.php fname=Arian lname=Shams <?php $var1 = $_POST[‘fname’]; $var2 = $_POST[‘lname’]; ?> Your form html or php file The process.php file that will process the request (which could be the same as the posting file)
  • 15. Passing Variable to PHP (GET) www.site.com/index.php?query=ischool&lang=en Start of query string key=value pairs Separator Note- certain characters cannot be put in the URL (such as space character). You will to “URL Encode” those special characters. For example, a space character will show up as a %20 in the URL query string. <?php $var1 = $_GET[‘query’]; $var2 = $_GET[‘lang’]; ?>
  • 16. Security (SQL Injection and XSS) HTTP POST Request fname=Arian lname=SQL Code In your PHP… $query = “INSERT INTO table (fname, lname)”; $query .= “VALUES (‘{$_POST[‘fname’]}’, ‘{$_POST[‘lname’]}’);” A malicious user can submit (POST or GET) • SQL Code  SQL Injection Attack, or • HTML tags that could be anything from a form to a <script> tag  XSS Attack.
  • 17. Preventing SQL Injection & XSS To prevent this, you have to sanitize your input variables and make sure you output safe HTML //Sanitize  SQL Injection $sanitized_variable = $db->real_escape_string($_POST[‘lname’]); //Output Safe HTML  XSS echo htmlspecialchars($row[‘lname’]); You can try to sanitize for HTML tags by using strip_tags($_POST[]) before you input the value into the database. Just make sure that is what you want to do…
  • 18. Additional Security Tip Don’t type out the username and password when instantiating mysqli. Instead, create a special PHP file that defines certain constants outside the root of your website which you can then include and use in your PHP code. define(SQL_PASSWORD, “mypassword”);
  • 19. Demo Time DEMO Constant Definitions constants.php Use of $_GET localhost/sports/team.php?id=1 Regular Posting localhost/sports/players.php Use of $_POST and INSERT localhost/sports/addPlayer-process.php Multiselect/Array Posting localhost/sports/editRoster.php?id=1 Use of $_POST arrays localhost/sports/editRoster-process.php Deleting localhost/sports/deletePlayer-process.php?id=1
  • 20. Additional Notes about POSTing • If a checkbox input is not checked, that variable will NOT be passed in the POST (or GET) – Use isset() to see if a variable exists: isset($_POST[]); • POSTing an array of variables to PHP (such as a multiselect) requires you to append brackets to the name of the input type. <select multiple=“multiple” name=“mylist[]”>…
  • 21. Next Time You Choose the Topic! Email me with PHP and/or database topics you would like to review and I will select the questions that seems like it would benefit the class the most. I will take the first 15 minutes to review the first two sessions but then after that the floor is open to the topics you choose.