SlideShare ist ein Scribd-Unternehmen logo
1 von 21
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.

Weitere ähnliche Inhalte

Ähnlich wie php2.pptx

Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2ADARSH BHATT
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Advanced Php - Macq Electronique 2010
Advanced Php - Macq Electronique 2010Michelangelo van Dam
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For BeginnersJonathan Wage
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate 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 FrameworksNate 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 2018Adam Tomat
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQLddiers
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11Michelangelo van Dam
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebMikel 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
 

Ähnlich wie 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
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
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
 

Kürzlich hochgeladen

Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 

Kürzlich hochgeladen (20)

Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 

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.