Chapters 10 & 11 PHP AND MYSQL

Similar documents
A Crash Course in PDO

Professional PHP for working with MySQL

CHAPTER 10. Connecting to Databases within PHP

COMP284 Scripting Languages Lecture 13: PHP (Part 5) Handouts

Lecture 13: MySQL and PHP. Monday, March 26, 2018

Systems Programming & Scripting

Networks and Web for Health Informatics (HINF 6220) Tutorial 13 : PHP 29 Oct 2015

Options. Real SQL Programming 1. Stored Procedures. Embedded SQL

Development Technologies. Agenda: phpmyadmin 2/20/2016. phpmyadmin MySQLi. Before you can put your data into a table, that table should exist.

LAB 11 WORKING WITH DATABASES

Using PHP with MYSQL

CPET 499/ITC 250 Web Systems

OpenEMR ZF2 Module Installer. 1. Authentication to Database and SQL Query Handling. 1.1 Zend\Db\Adapter. Introduction

Managing Multiple Database Tables

How to use PHP with a MySQL database

escuela técnica superior de ingeniería informática

PHP Development - Introduction

Web Systems Nov. 2, 2017

Executing Simple Queries

Chapter 7 PHP Files & MySQL Databases

; Magic quotes for runtime-generated data, e.g. data from SQL, from exec(), etc. magic_quotes_runtime = Off

SQL Injection Attack Lab

CSE 127: Computer Security SQL Injection. Vector Li

You can use Dreamweaver to build master and detail Web pages, which

PHP MySQLi Class Documentation

4) PHP and MySQL. Emmanuel Benoist. Spring Term Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 1

MySQL: Access Via PHP

Database Connectivity using PHP Some Points to Remember:

Static Webpage Development

MySQL: Querying and Using Form Data

APLIKACJE INTERNETOWE 8 PHP WYKORZYSTANIE BAZY DANYCH MYSQL

Lecture 7: Web hacking 3, SQL injection, Xpath injection, Server side template injection, File inclusion

PHP for PL/SQL Developers. Lewis Cunningham JP Morgan Chase

Slide 1. Chapter 5. How to use the MVC pattern to organize your code. 2010, Mike Murach & Associates, Inc. Murach's PHP and MySQL, C5

CSCI 4000 Assignment 4

Comp 519: Web Programming Autumn 2015

By the end of this chapter, you will have a very basic, but fully functional blogging system.

School of Information and Computer Technology Sirindhorn International Institute of Technology Thammasat University

Web development using PHP & MySQL with HTML5, CSS, JavaScript

Smart Bulk SMS & Voice SMS Marketing Script with 2-Way Messaging. Quick-Start Manual

Troubleshooting. The NLR Web Interface Does not Appear CHAPTER

Host at 2freehosting.Com

CSCI 4000 Assignment 5

CERTIFICATE IN WEB PROGRAMMING

Server-side web security (part 2 - attacks and defences)

Shell Scripting. Todd Kelley CST8207 Todd Kelley 1

Daniel Pittman October 17, 2011

Build a Subfile with PHP

Create Basic Databases and Integrate with a Website Lesson 3

IELM 511 Information Systems Design Labs 5 and 6. DB creation and Population

Prepared Statement. Always be prepared

Web accessible Databases PHP

Unit 27 Web Server Scripting Extended Diploma in ICT

CONTENTS IN DETAIL INTRODUCTION 1 THE FAQS OF LIFE THE SCRIPTS EVERY PHP PROGRAMMER WANTS (OR NEEDS) TO KNOW 1 2 CONFIGURING PHP 19

Side-channel attacks (and blind SQL injections)

CSCI 4000 Assignment 6

Locate your Advanced Tools and Applications

Mobile Forms Integrator

Programming for the Web with PHP

Courtesy of Clayton Fyfe. Lab 2 Runthrough

Mount Saint Mary College, Newburgh, NY Internet Programming III - CIT310

Vesta Control Panel is a stack of software components which is roughly divided into two main layers as shown below in the architecture diagram.

Adding A PHP+MySQL Hit Counter to your Website

B. V. Patel Institute of BMC & IT 2014

Introduction to PHP. Handling Html Form With Php. Decisions and loop. Function. String. Array

This lecture. PHP tags

Module - P7 Lecture - 15 Practical: Interacting with a DBMS

LAMP Apps. Overview. Learning Outcomes: At the completion of the lab you should be able to:

Jacksonville Linux User Group Presenter: Travis Phillips Date: 02/20/2013

ITS331 IT Laboratory I: (Laboratory #11) Session Handling

Databases PHP I. (GF Royle, N Spadaccini ) PHP I 1 / 24

Introduction to SQL on GRAHAM ED ARMSTRONG SHARCNET AUGUST 2018

PHP and MySQL Programming

Simple sets of data can be expressed in a simple table, much like a

Overview of MySQL Structure and Syntax [2]

Product: DQ Order Manager Release Notes

Web insecurity Security strategies General security Listing of server-side risks Language specific security. Web Security.

PHP APIs. Rapid Learning & Just In Time Support

Chapter 1 An introduction to relational databases and SQL

MYSQL DATABASE ACCESS WITH PHP

Ark Database Documentation

Andowson Chang

PHP INTERVIEW QUESTION-ANSWERS

Adrien Poupa TP040869

PHP: Hypertext Preprocessor. A tutorial Introduction

How to create secure web sites

SQL. Often times, in order for us to build the most functional website we can, we depend on a database to store information.

Textbook. Topic 8: Files and Exceptions. Files. Types of Files

Chapter 10: MySQL & PHP. PHP and MySQL CIS 86 Mission College

COM1004 Web and Internet Technology

Using PHPMyAdmin with WordPress

A shell can be used in one of two ways:

CSE 154 LECTURE 23:RELATIONAL DATABASES AND SQL

Using.htaccess to Restrict OU Directory by Usernames and Passwords in an.htpasswd File

Part I Quick Start Installation 2. Part II Manual Installation 8. Part III Ixed directory 10

Advanced Web Technology 10) XSS, CSRF and SQL Injection

PHP: Cookies, Sessions, Databases. CS174. Chris Pollett. Sep 24, 2008.

Injection. CSC 482/582: Computer Security Slide #1

COMP519: Web Programming Autumn 2015

PHP Reference. To access MySQL manually, run the following command on the machine, called Sources, where MySQL and PhP have been installed:

Transcription:

Chapters 10 & 11 PHP AND MYSQL

Getting Started The database for a Web app would be created before accessing it from the web. Complete the design and create the tables independently. Use phpmyadmin, for example:

Connecting to a Database PHP offers three different ways to connect to and interact with a MySQL database: 1. Original MySQL extension no longer developed, not recommended 2. MySQL Improved: MySQLi designed specifically for MySQL, so is not easily portable to other databases Procedural implementation (functions) Objects implementation Works for PHP versions < 5.1 3. PHP Data Objects: PDO software neutral, preferable if database flexibility is important. We will focus on PDO

Communicating to the MySQL Database All PHP implementations follow the same sequence: 1. Connect to the MySQL database using the hostname, username, password, and database name. 2. Prepare an SQL query. 3. Execute the query and save the result. 4. Extract the data from the result or confirm the result. 5. Close the connection to the database.

The Connection File <?php /*This file contains the database access information. It should be called pdo_connect.php or something similar*/ // Set the database access information as constants using your DB credentials where indicated: define(dbconnstring,'mysql:host=127.0.0.1;dbname='yourdb'); define(dbuser, 'yourusername'); define(dbpass, 'yoursqlpassword');

Saving the Connection File Important security measure: 1. Place the pdo_connect.php file outside of the public_html directory. 2. Set file permissions on pdo_connect.php to 644.

Connecting to the Database using PDO PDO throws an exception if the connection fails. In development, we need to know the details of the exception In production, we would change the catch block to redirect to a generic error page. Wrap the code in a try catch block and use the constants you defined: try { $conn= new PDO(DBCONNSTRING, DBUSER, DBPASS); } catch (PDOException $e) { } echo $e->getmessage(); //for development only //for deployment (we will learn about the header function soon): // header("location: http://localhost/app/errors.php");

Calling the Connection/Config File Use '../' to go up one level in your folder structure to reference the pdo_connect.php file. Use as many../ as needed. Use the require_once() function, which will halt the script if it is unsuccessful, to connect to the database: <?php require_once ('../pdo_connect.php');?>

The Query Write the SQL query as a PHP string Assign it to a PHP variable. Some things to remember: SQL keywords are not case-sensitive; using all caps is conventional to aid readability Database table names and column names are casesensitive SQL strings must be in quotes (either single or double as long as they match) SQL numeric values are not enclosed in quotes

Creating SQL Queries with PHP Assign the SQL query as a string to a PHP variable. (When possible, test the query first in phpmyadmin to cut down on errors.) $sql = "INSERT INTO JJ_contacts (firstname, lastname, emailaddr, comments, newsletter) VALUES ('$firstname', '$lastname', '$email', '$comments', $howhear)"; Remember that SQL variables are case-sensitive you must reference them exactly as they are in the database (SQL keywords are not case-sensitive.) The semicolon ends the PHP string. It isn't required for the SQL in this case.

Executing Queries with PDO Execute the query by calling the query() method on the connection object (which was assigned in the php_config file) and passing the query string. Assign the result to a new variable: $result = $conn->query($sql); For simple queries like, INSERT, UPDATE, DELETE, etc. (which don't return records), the function will return either TRUE or FALSE. The exec() method can also be used for simple queries. It returns the number of rows affected. For complex queries like SELECT, which return results of the query as a table, $result will be a pointer to the returned table or FALSE if it did not work.

PDO Errors The third element of this array is only created if something went wrong, so that is where to check for errors.

Checking SELECT Queries for Errors To determine if there was a problem with the query, check the third element in the array of error messages from the database which will be in the connection object's errorinfo() method: $errorinfo = $conn->errorinfo(); if (isset($errorinfo[2])) echo $errorinfo[2]; else $numrows = $result->rowcount(); Note that $errorinfo[2] is not necessarily the output you want your users to see. Change it to something more general before deployment.

Processing SELECT Queries It is not necessary to count the number of rows in the result table, but the rowcount() method of the $result object will have it if needed: $numrows = $result->rowcount(); A foreach loop can handle processing for all rows: <?php foreach ($conn->query($sql) as $row) {?> <tr> <td><?php echo $row['image_id'];?></td> <td><?php echo $row['filename'];?></td> <td><?php echo $row['caption'];?></td> </tr> <?php } //endforeach loop?>

Processing SELECT Queries Where do the $row array key values come from? <?php foreach ($conn->query($sql) as $row) {?> <tr> <td><?php echo $row['image_id'];?></td> <td><?php echo $row['filename'];?></td> <td><?php echo $row['caption'];?></td> </tr> <?php } //endforeach loop?>

More Specific SELECT Queries $sql = 'SELECT filename, caption FROM JJ_images WHERE image_id=6'; $sql = 'SELECT filename, caption FROM JJ_images WHERE caption LIKE "%Kyoto%"'; $sql = 'SELECT filename, caption FROM JJ_images WHERE caption LIKE BINARY "%maiko%"'; String search using LIKE comparison operator and wildcard character % Case-sensitive string comparison

SQL Injection SELECT * FROM users WHERE username='abc' AND pw='123' SELECT * FROM users WHERE username='abc' AND pw='123' OR 1=1 When the query is derived from a variable or from user input, it is critical to process the query safely: 1. Check that expected values are the correct type e.g. is_numeric() 2. Escape user input 3. Use prepared statements

Numeric User Input in a Query

Numeric User Input in a Query

Numeric User Input in a Query

User Registration

Inserting User Input to the Database SQL Name Field

Inserting User Input to the Database In the self-processing form, once the user s submission is acceptable, the data can be sent to the database.

Inserting User Input to the Database tinyint Re-work the handling of subscribe $sql = "INSERT into JJ_contacts (firstname, lastname, emailaddr, comments, newsletter) VALUES ('$firstname', '$lastname', '$email', '$comments', $subscribe)"; No quotes for an integer variable

Prepared Statements Important security features A template of an SQL query Uses placeholders for each variable Prevents SQL injection attacks: quotes and other characters are automatically escaped before the query is executed More efficient when the same query is used more than once Binding the results from each column makes output easier to display

Prepared Statements Both MySQLi and PDO use question marks as anonymous placeholders for column values. The execution is the same: 1. Initialize the statement 2. Prepare the statement 3. Bind values to the placeholders 4. Execute the statement 5. Bind the results (optional) 6. Store the results (optional) 7. Fetch the result 8. Close the statement to free the memory used.

Prepared Statements Instead of: Prepare, Bind, Execute:

Prepared Statements An advantage of PDO is that it allows for named placeholders:

Close the existing connection $statement->closecursor(); Optional because PHP will close the connection at the end of the script Makes for good programming form anyway

PDO Connection Crib Sheet

Some methods of the PDO class prepare($sql_statement) lastinsertid() Some methods of the PDOStatement class bindvalue($param, $value) execute() fetchall() fetch() rowcount() closecursor()