Accessing MySQL Using PDO Charles Severance www.php-intro.com.

Slides:



Advertisements
Similar presentations
Introduction to PHP Dr. Charles Severance
Advertisements

Keys, Referential Integrity and PHP One to Many on the Web.
Manipulating MySQL Databases with PHP. PHP and mySQL2 Objectives Connect to MySQL from PHP Learn how to handle MySQL errors Execute SQL statements with.
Accessing MySQL Using PDO
Getting PHP Hosting Dr. Charles Severance. What We Need We want to be able to put up our application on the web so anyone can access our URL (and so we.
PHP Scripts HTML Forms Two-tier Software Architecture PHP Tools.
Forms and PHP Dr. Charles Severance
Cookies, Sessions, and Authentication Dr. Charles Severance
Check That Input Preventing SQL Injection Attacks By Andrew Morton For CS 410.
SJSU CS157B Dr. Lee1  2004 Jenny Mitchell Two Useful Tools You Can’t Live Without by Jenny Mitchell SJSU CS157B Section PHP and MySQL.
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
PHP Security.
Databases with PHP A quick introduction. Y’all know SQL and Databases  You put data in  You get data out  You can do processing on it very easily 
Session 5: Working with MySQL iNET Academy Open Source Web Development.
INTERNET APPLICATION DEVELOPMENT For More visit:
Create an online booking system (login/registration)
PDO, PHP Data Object Use a Database with PHP
Analysis of SQL injection prevention using a proxy server By: David Rowe Supervisor: Barry Irwin.
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
© 2003 By Default! A Free sample background from Slide 1 Week 2  Free PHP Hosting Setup  PHP Backend  Backend Security 
Accessing MySQL with PHP IDIA 618 Fall 2014 Bridget M. Blodgett.
Introduction to MySQL Lab no. 10 Advance Database Management System.
Installing and Using MySQL and phpMyAdmin. Last Time... Installing Apache server Installing PHP Running basic PHP scripts on the server Not necessary.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
PHP Part 2.
NMD202 Web Scripting Week3. What we will cover today Includes Exercises PHP Forms Exercises Server side validation Exercises.
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Accessing Your MySQL Database from the Web with PHP (Ch 11) 1.
CHAPTER 9 PHP AND MYSQL. A POSSIBLE SITE CONFIGURATION Application Folder index.php includes (folder)header.phpfooter.phpstyle.cssmodel (folder)mysqli_connect.php.
HTML, PHP, and MySQL: Putting It All Together. Making a Form Input tags Types: “text” “radio” “checkboxes” “submit”
CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Address: Course Page:
Introduction to Dynamic Web Content Dr. Charles Severance
Creating a simple database This shows you how to set up a database using PHPMyAdmin (installed with WAMP)
Chapter 8 Manipulating MySQL Databases with PHP PHP Programming with MySQL 2 nd Edition.
CHAPTER 10 PHP MySQL Database
CSC 2720 Building Web Applications Accessing MySQL from PHP.
Relational Databases and MySQL. Relational Databases Relational databases model data by storing rows and columns in tables. The power of the relational.
Accessing MySQL Using PDO Charles Severance
Forms and PHP Dr. Charles Severance
Relational Databases and MySQL Charles Severance
Fundamentals of Web DevelopmentRandy Connolly and Ricardo HoarFundamentals of Web DevelopmentRandy Connolly and Ricardo Hoar Fundamentals of Web DevelopmentRandy.
PHP Arrays Dr. Charles Severance
PHP Functions / Modularity Dr. Charles Severance
Using Handlebars Dr. Charles Severance
Introduction to Dynamic Web Content Dr. Charles Severance
Web Systems & Technologies
Dr. Charles Severance Using Handlebars Dr. Charles Severance
Accessing MySQL Using PDO
C.R.U.D. Charles Severance
Introduction to Dynamic Web Content
Transactions Dr. Charles Severance
Using JSON Dr. Charles Severance
Redirect, Routing, and Authentication
Relational Databases and MySQL
HTTP Parameters and Arrays
Unix System Administration
Web Design and Development
Accessing MySQL Using PDO
PHP / MySQL Introduction
ISC440: Web Programming 2 Server-side Scripting PHP 3
Web Systems Development (CSC-215)
Introduction to Dynamic Web Content
Using jQuery Dr. Charles Severance
Tutorial 6 PHP & MySQL Li Xu
Charles Severance Single Table SQL.
Model View Controller (MVC)
Presentation transcript:

Accessing MySQL Using PDO Charles Severance

Web ServerDatabase Server Time Apache PHP MySql Browser JavaScri pt DOMDOM ind.ph p PDOPDO Parse Respons e Parse Reques t

Application Structure Database Data Model Application Software (i.e. PHP) EndUser Developer DBA Database Tools (i.e. phpMyAdmin) SQL SQL

Multiple Ways to Access MySql PHP is evolving - there are three ways to access MySql Legacy non-OO mysql_ routines (deprecated) New mysqli (OO version that is similar to mysql_) PDO - Portable Data Objects A perfect topic for debate

Creating a Database and User CREATE DATABASE misc; GRANT ALL ON misc.* TO IDENTIFIED BY 'zap'; GRANT ALL ON misc.* TO IDENTIFIED BY 'zap'; USE misc; (if you are in the command line) /Applications/MAMP/Library/bin/mysql -u root -P p /Applications/xampp/xamppfiles/bin/mysql -u root -p c:\xampp\mysql\bin\mysql.exe

Creating a Table CREATE TABLE users ( user_id INTEGER NOT NULL AUTO_INCREMENT KEY, name VARCHAR(128), VARCHAR(128), password VARCHAR(128), INDEX( ) ) ENGINE=InnoDB CHARSET=utf8; mysql> describe users; | Field | Type | Null | Key | Default | Extra | | user_id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(128) | YES | | NULL | | | | varchar(128) | YES | MUL | NULL | | | password | varchar(128) | YES | | NULL | |

Inserting a Few Records INSERT INTO users (name, ,password) VALUES INSERT INTO users (name, ,password) VALUES mysql> select * from users; | user_id | name | | password | | 1 | Chuck | | 123 | | 2 | Glenn | | 456 |

Database Connection Hostname miscsakai users

Database Connection PHPSoftware SQL Hostname miscsakai id / password users $pdo = new PDO('mysql:host=localhost;port=8889;dbname=misc', 'fred', 'zap'); pdo.php 3306 for xampp/linux

<?php echo " \n"; $pdo=new PDO('mysql:host=localhost;port=8889;dbname=misc', 'fred', 'zap'); $stmt = $pdo->query("SELECT * FROM users"); while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { print_r($row); } echo " \n";?> Array( [user_id] => 1 [name] => Chuck [ ] => [password] => 123 ) Array( [user_id] => 2 [name] => Glenn [ ] => [password] => 456 ) mysql> select * from users; | user_id | name | | password | | 1 | Chuck | | 123 | | 2 | Glenn | | 456 | first.php

<?php $pdo = new PDO('mysql:host=localhost;port=8889;dbname=misc', 'fred', 'zap'); $stmt = $pdo->query("SELECT name, , password FROM users"); echo ' '."\n"; while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { echo " "; echo($row['name']); echo(" "); echo($row[' ']); echo(" "); echo($row['password']); echo(" \n"); } echo " \n";?> Chuck 123 Glenn 456 second.php

Pattern Put database connection information in a single file and include it in all your other files Helps make sure to not to mistakenly reveal id / pw Don't check it into a public source repository :)

<?php $pdo = new PDO('mysql:host=localhost;port=8889;dbname=misc', 'fred', 'zap'); // See the "errors" folder for details... $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); <?php echo " \n"; require_once "pdo.php"; $stmt = $pdo->query("SELECT * FROM users"); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ print_r($row); } echo " \n";?> pdo.php third.php Array( [user_id] => 1 [name] => Chuck [ ] => [password] => 123 ) Array( [user_id] => 2 [name] => Glenn [ ] => [password] => 456 ) 3306 for xampp/linux

Lets put some data in a database!

<?php require_once "pdo.php"; if ( isset($_POST['name']) && isset($_POST[' ']) && isset($_POST['password'])) { $sql = "INSERT INTO users (name, , password) VALUES (:name, : , :password)"; echo(" \n".$sql."\n \n"); $stmt = $pdo->prepare($sql); $stmt->execute(array( ':name' => $_POST['name'], ': ' => $_POST[' '], ':password' => $_POST['password'])); } ?> Add A New User Name: Password: user1.php

mysql> select * from users; | user_id | name | | password | | 1 | Chuck | | 123 | | 2 | Glenn | | 456 | | 3 | Fred | | YO | user1.php

if ( isset($_POST['name']) && isset($_POST[' ']) && isset($_POST['password'])) { $sql = "INSERT INTO users (name, , password) VALUES (:name, : , :password)"; echo(" \n".$sql."\n \n"); $stmt = $pdo->prepare($sql); $stmt->execute(array( ':name' => $_POST['name'], ': ' => $_POST[' '], ':password' => $_POST['password'])); } ?> <?php $stmt = $pdo->query("SELECT name, , password FROM users"); while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { echo " "; echo($row['name']); echo(" "); echo($row[' ']); echo(" "); echo($row['password']); echo(" \n"); } ?> Add A New User user2.php

<?php require_once "pdo.php"; if ( isset($_POST['user_id']) ) { $sql="DELETE FROM users WHERE user_id = :zip"; echo " \n$sql\n \n"; $stmt = $pdo->prepare($sql); $stmt->execute(array(':zip'=>$_POST['user_id'])); } ?> Delete A User ID to Delete: user2del.php

<?php require_once "pdo.php"; if ( isset($_POST['user_id']) ) { $sql="DELETE FROM users WHERE user_id = :zip"; echo " \n$sql\n \n"; $stmt = $pdo->prepare($sql); $stmt->execute(array(':zip'=>$_POST['user_id'])); } ?> Delete A User ID to Delete: user2del.php

mysql> select * from users; | user_id | name | | password | | 1 | Chuck | | 123 | | 2 | Glenn | | 456 |

user3.php

if ( isset($_POST['delete']) && isset($_POST['user_id']) ) { $sql = "DELETE FROM users WHERE user_id = :zip"; echo " \n$sql\n \n"; $stmt = $pdo->prepare($sql); $stmt->execute(array(':zip' => $_POST['user_id'])); } ?> <?php $stmt = $pdo->query("SELECT name, , password, user_id FROM users"); while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { echo " "; echo($row['name']); echo(" "); echo($row[' ']); echo(" "); echo($row['password']); echo(" "); echo(' <input type="hidden" '); echo('name="user_id" value="'.$row['user_id'].'">'."\n"); echo(' '); echo("\n \n"); echo(" \n"); } user3.php

echo(' <input type="hidden" '); echo('name="user_id" value="'.$row['user_id'].'">'."\n"); echo(' '); echo("\n \n"); Fred YO if ( isset($_POST['delete']) && isset($_POST['user_id']) ) { $sql = "DELETE FROM users WHERE user_id = :zip"; echo " \n$sql\n \n"; $stmt = $pdo->prepare($sql); $stmt->execute(array(':zip' => $_POST['user_id'])); }

if ( isset($_POST['delete']) && isset($_POST['user_id']) ) { $sql = "DELETE FROM users WHERE user_id = :zip"; echo " \n$sql\n \n"; $stmt = $pdo->prepare($sql); $stmt->execute(array(':zip' => $_POST['user_id'])); }

<?php require_once "pdo.php"; if ( isset($_POST['name']) && isset($_POST[' ']) && isset($_POST['password'])) { $sql = "INSERT INTO users (name, , password) VALUES (:name, : , :password)"; echo(" \n".$sql."\n \n"); $stmt = $pdo->prepare($sql); $stmt->execute(array( ':name' => $_POST['name'], ': ' => $_POST[' '], ':password' => $_POST['password'])); } if ( isset($_POST['delete']) && isset($_POST['user_id']) ) { $sql = "DELETE FROM users WHERE user_id = :zip"; echo " \n$sql\n \n"; $stmt = $pdo->prepare($sql); $stmt->execute(array(':zip' => $_POST['user_id'])); } ?> Program Outline <?php require_once "pdo.php";I f ( isset($_POST['name']) && isset($_POST[' ']) && isset($_POST['password'])) { $sql = "INSERT INTO users (name, , password) VALUES (:name, : , :password)"; echo(" \n".$sql."\n \n"); $stmt = $pdo->prepare($sql); $stmt->execute(array( ':name' => $_POST['name'], ': ' => $_POST[' '], ':password' => $_POST['password'])); } if ( isset($_POST['delete']) && isset($_POST['user_id']) ) { $sql = "DELETE FROM users WHERE user_id = :zip"; echo " \n$sql\n \n"; $stmt = $pdo->prepare($sql); $stmt->execute(array(':zip' => $_POST['user_id'])); } ?> <?php $stmt = $pdo->query("SELECT name, , password, user_id FROM users"); while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { echo " "; echo($row['name']); echo(" "); echo($row[' ']); echo(" "); echo($row['password']); echo(" "); echo(' <input type="huser_idden" '); echo('name="user_id" value="'.$row['user_id'].'">'."\n"); echo(' '); echo("\n \n"); echo(" \n"); } ?> Add A New User Name: Password: < p>

<?php $stmt = $pdo->query("SELECT name, , password, user_id FROM users"); while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { echo " "; echo($row['name']); echo(" "); echo($row[' ']); echo(" "); echo($row['password']); echo(" "); echo(' <input type="hidden" '); echo('name="user_id" value="'.$row['user_id'].'">'."\n"); echo(' '); echo("\n \n"); echo(" \n"); } ?> <?php require_once "pdo.php";I f ( isset($_POST['name']) && isset($_POST[' ']) && isset($_POST['password'])) { $sql = "INSERT INTO users (name, , password) VALUES (:name, : , :password)"; echo(" \n".$sql."\n \n"); $stmt = $pdo->prepare($sql); $stmt->execute(array( ':name' => $_POST['name'], ': ' => $_POST[' '], ':password' => $_POST['password'])); } if ( isset($_POST['delete']) && isset($_POST['user_id']) ) { $sql = "DELETE FROM users WHERE user_id = :zip"; echo " \n$sql\n \n"; $stmt = $pdo->prepare($sql); $stmt->execute(array(':zip' => $_POST['user_id'])); } ?> <?php $stmt = $pdo->query("SELECT name, , password, user_id FROM users"); while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { echo " "; echo($row['name']); echo(" "); echo($row[' ']); echo(" "); echo($row['password']); echo(" "); echo(' <input type="huser_idden" '); echo('name="user_id" value="'.$row['user_id'].'">'."\n"); echo(' '); echo("\n \n"); echo(" \n"); } ?> Add A New User Name: Password: < p>

Add A New User Name: Password: Program Outline <?php require_once "pdo.php";I f ( isset($_POST['name']) && isset($_POST[' ']) && isset($_POST['password'])) { $sql = "INSERT INTO users (name, , password) VALUES (:name, : , :password)"; echo(" \n".$sql."\n \n"); $stmt = $pdo->prepare($sql); $stmt->execute(array( ':name' => $_POST['name'], ': ' => $_POST[' '], ':password' => $_POST['password'])); } if ( isset($_POST['delete']) && isset($_POST['user_id']) ) { $sql = "DELETE FROM users WHERE user_id = :zip"; echo " \n$sql\n \n"; $stmt = $pdo->prepare($sql); $stmt->execute(array(':zip' => $_POST['user_id'])); } ?> <?php $stmt = $pdo->query("SELECT name, , password, user_id FROM users"); while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { echo " "; echo($row['name']); echo(" "); echo($row[' ']); echo(" "); echo($row['password']); echo(" "); echo(' <input type="huser_idden" '); echo('name="user_id" value="'.$row['user_id'].'">'."\n"); echo(' '); echo("\n \n"); echo(" \n"); } ?> Add A New User Name: Password: < p>

Recall HTML Injection...

Input Guess <input type="text" name="guess" id="guess" value=""> DIE DIE " />

SQL Injection SQL injection or SQLi is a code injection technique that exploits a security vulnerability in some computer software. An injection occurs at the database level of an application (like queries). The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and unexpectedly executed. Using well designed query language interpreters can prevent SQL injections.

SQL Injection This code does it all in a select instead of a prepare/execute pattern but it is prone to SQL Injection – where and why? if ( isset($_POST[' ']) && isset($_POST['password']) ) { $e = $_POST[' ']; $p = $_POST['password']; $sql = "SELECT name FROM users WHERE = '$e' AND password = '$p'"; $stmt = $pdo->query($sql); login1.php Note: For PHP < 5.4 – this might not fail, actually – look up "stripslashes"

What Could Go Wrong? login1.php

if ( isset($_POST[' ']) && isset($_POST['password']) ) { $e = $_POST[' ']; $p = $_POST['password']; $sql = "SELECT name FROM users WHERE = '$e' AND password = '$p'"; $stmt = $pdo->query($sql); login1.php

Use Prepared Statements Properly login2.php if ( isset($_POST[' ']) && isset($_POST['password']) ) { echo("Handling POST data...\n"); $sql = "SELECT name FROM users WHERE = :em AND password = :pw"; echo " \n$sql\n \n"; $stmt = $pdo->prepare($sql); $stmt->execute(array( ':em' => $_POST[' '], ':pw' => $_POST['password'])); $row = $stmt->fetch(PDO::FETCH_ASSOC); When the statement is executed, the placeholders get replaced with the actual strings and everything is automatically escaped!

PDO Error Handling: What Could Go Wrong?

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $stmt = $pdo->prepare("SELECT * FROM users where user_id = :xyz"); $stmt->execute(array(":xyz" => $_GET['user_id'])); $row = $stmt->fetch(PDO::FETCH_ASSOC); if ( $row === false ) { echo(" user_id not found \n"); } else { echo(" user_id found \n"); } errors/error0.ph p

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $stmt = $pdo->prepare("SELECT * FROM users where user_id = :xyz"); $stmt->execute(array(":pizza" => $_GET['user_id'])); $row = $stmt->fetch(PDO::FETCH_ASSOC); if ( $row === false ) { echo(" user_id not found \n"); } else { echo(" user_id found \n"); } errors/error1.ph p

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $stmt = $pdo->prepare("SELECT * FROM users where user_id = :xyz"); $stmt->execute(array(":pizza" => $_GET['user_id'])); $row = $stmt->fetch(PDO::FETCH_ASSOC); if ( $row === false ) { echo(" user_id not found \n"); } else { echo(" user_id found \n"); } errors/error1.php

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare("SELECT * FROM users where user_id = :xyz"); $stmt->execute(array(":pizza" => $_GET['user_id'])); $row = $stmt->fetch(PDO::FETCH_ASSOC); if ( $row === false ) { $_SESSION['error'] = 'Bad value for user_id'; header( 'Location: index.php' ) ; return; } errors/error2.php

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); try { $stmt = $pdo->prepare("SELECT * FROM users where user_id = :xyz"); $stmt->execute(array(":pizza" => $_GET['user_id'])); } catch (Exception $ex ) { echo("Exception message: ".$ex->getMessage()); return; } $row = $stmt->fetch(PDO::FETCH_ASSOC); errors/error3.php

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); try { $stmt = $pdo->prepare("SELECT * FROM users where user_id = :xyz"); $stmt->execute(array(":pizza" => $_GET['user_id'])); } catch (Exception $ex ) { echo("Internal error, please contact support"); error_log("error4.php, SQL error=".$ex->getMessage()); return; } $row = $stmt->fetch(PDO::FETCH_ASSOC); errors/error4.php

Where do error_log()'s go? When in doubt look at PHPInfo

Where do error_log()'s go? File Paths: /Applications/MAMP/logs/php_error.log c:\xampp\php\logs\php_error_log Open the log file and scroll to the bottom Watch the log actively On Mac / Linux use: tail -f filename Windows:

Summary Making database connections Doing database operations SQL security (a.k.a. we love PDO prepared statements) Exploring errors...

Acknowledgements / Contributions These slides are Copyright Charles R. Severance ( as part of and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials. Initial Development: Charles Severance, University of Michigan School of Information Insert new Contributors and Translators here including names and dates Continue new Contributors and Translators here