+ All Categories
Home > Documents > 20110713 Webinar Mysql Php v1

20110713 Webinar Mysql Php v1

Date post: 06-Mar-2015
Category:
Upload: pushpasrinivasan
View: 35 times
Download: 1 times
Share this document with a friend
48
Transcript
Page 1: 20110713 Webinar Mysql Php v1
Page 2: 20110713 Webinar Mysql Php v1

<Insert Picture Here>

Building High Performance and High Traffic PHP Applications with MySQL - Part 1: The Fundamentals

Johannes SchlüterMySQL Engineering: Connectors & Client Connectivity

Wei-Chen ChiuMySQL Product Marketing Manager

Page 3: 20110713 Webinar Mysql Php v1

© 2011 Oracle Corporation – Proprietary and Confidential

About MySQL

• Founded in 1995

• Acquired by Sun Microsystems in February 2008

• Acquired by Oracle in January 2010

• The World’s Most Popular Open Source

Database

• MySQL Commercial Editions Available

Page 4: 20110713 Webinar Mysql Php v1

© 2011 Oracle Corporation – Proprietary and Confidential

Oracle’s Investment in MySQL

• Make MySQL a Better MySQL- #1 Open Source Database for Web Applications

- MySQL 5.5 GA – Better Performance and Scalability

• Develop, Promote and Support MySQL- Improve engineering, consulting and support

- MySQL Track at Oracle OpenWorld 2011

- Leverage 24x7, World-Class Oracle Support

• MySQL Community Edition- Source and binary releases

- GPL license

Page 5: 20110713 Webinar Mysql Php v1

© 2011 Oracle Corporation – Proprietary and Confidential

MySQL Powers the Web

Enterprise 2.0SaaS, Hosting

Web OEM / ISV’s

Telecommunication

s

MySQL Customers

Page 6: 20110713 Webinar Mysql Php v1

<Insert Picture Here>

Johannes SchlüterMySQL Engineering: Connectors & Client Connectivity

Building High Performance and High Traffic PHP Applications with MySQL - Part 1: The Fundamentals

Page 7: 20110713 Webinar Mysql Php v1

<Insert Picture Here>

Introduction And Installation

Page 8: 20110713 Webinar Mysql Php v1

Introduction to PHP

• PHP Hypertext Preprocessor

• Web-Centric Scripting Language

– Processed by a Web-Server module

– Can be embedded in HTML

– Built-in functionality for dealing with Web-Things

• Developed by a large Open Source community since 1995

– Multiple Oracle employees actively involved

• PHP consists out of a relatively small core and a large collection of function libraries (“extensions”)

• http://php.net

Page 9: 20110713 Webinar Mysql Php v1

Installation

• You need:

– A Web Server (Apache HTTPd, Oracle Web Server, Microsoft IIS, nginx, …)

– MySQL Server

– PHP runtime

• Tip: Prepackaged bundles ease the initial setup

– XAMPP

• Tip: Integrated Development Environments (IDEs) help managing and editing code

Page 10: 20110713 Webinar Mysql Php v1

XAMPP

www.apachefriends.org/xampp

Page 11: 20110713 Webinar Mysql Php v1

IDE – NetBeans – www.netbeans.org

Page 12: 20110713 Webinar Mysql Php v1

Verifying the PHP Installation

c:\xampp\htdocs\test.php:

<?phpphpinfo();?>

http://localhost/test.php

Page 13: 20110713 Webinar Mysql Php v1

MySQL Workbench

Page 14: 20110713 Webinar Mysql Php v1

<Insert Picture Here>

Getting Started

Page 15: 20110713 Webinar Mysql Php v1

<?php$connection = mysqli_connect('localhost', 'root', '', 'test');if (!$connection) {

die('Error: ' . mysqli_connect_error());}$result = mysqli_query($connection,

'SELECT first_name, last_name FROM employees LIMIT 5');if (!$result) {

die('Error: ' . mysqli_error());}

echo “<table>\n”;while ($row = mysqli_fetch_assoc($result)) {

printf(“<tr><td>%s</td><td>%s</td></tr>\n”,htmlentities($row['first_name']),htmlentities($row['last_name'])

);}echo “</table>\n”;mysqli_free_result($result);mysqli_close($connection);?>

A First Example

Page 16: 20110713 Webinar Mysql Php v1

Adding New Data

<form action=”add.php” method=”post”><fieldset>

<label>Birth Date:</label><input type=”text” name=”birth_date”>

<label>First Name:</label><input type=”text” name=”first_name”>

<label>Last Name:</label><input type=”text” name=”last_name”>

<label>Gender:</label><select name=”gender”>

<option value=”M”>Male</option><option value=”F”>Female</option>

</select>

<input type=”submit” value=”Add Employee”></fieldset>

</form>

Page 17: 20110713 Webinar Mysql Php v1

First Step: Validation!

• Prevent mistakes by users

– The sooner a wrong input is detected the better it can be handled

• Might prevent some attacks

– No full security!

Page 18: 20110713 Webinar Mysql Php v1

Validation can be relatively easy ...

<?phpif (!isset($_POST['gender']) || !in_array($_POST['gender'], array('M', 'F')) {

// The user tried to bypass our system!die(“Invalid Gender”);

}

if (!isset($_POST['birth_date']) || !preg_math('/[0-9]{4}-[01][0-9]-[0-3][0-9]/', $_POST['birth_date']))

{// Maybe the user typed in something wrong?die(“Invalid date!”);

}?>

Page 19: 20110713 Webinar Mysql Php v1

Validation is hard!

• In some countries last names contain spaces

– Garcia Gonzalez

• Some countries have their own letters

– Schlüter

• Some countries use characters with special meanings to databases

– O'Harra

• I don't even talk about non-Latin alphabets :-)

Validation can't do everything we need!

– A validation might check the min. and max. length at least

– Validate your input, escape your output. Always.

Page 20: 20110713 Webinar Mysql Php v1

Escaping for mysqli

• mysqli_real_escape_string()

– Escapes special characters for usage in SQL statements

– Takes current encoding into account

$sql = sprintf(“INSERT INTO employees(birth_date, first_name, last_name, gender)VALUES ('%s', '%s', '%s', '%s')”,mysqli_real_escape_string($conn, $_POST['birth_date']),mysqli_real_escape_string($conn, $_POST['first_name']),mysqli_real_escape_string($conn, $_POST['last_name']),mysqli_real_escape_string($conn, $_POST['gender'])

);if ( ! mysqli_query($conn, $sql) {

// ERROR}

Page 21: 20110713 Webinar Mysql Php v1

Prepared Statements

Client Server

SELECT foo FROM barWHERE id = 42

•Create Execution plan•Query database

Resultset(s)

Page 22: 20110713 Webinar Mysql Php v1

Prepared Statements

Client Server

SELECT foo FROM barWHERE id = ?

Handle

•Create Execution plan

Page 23: 20110713 Webinar Mysql Php v1

Prepared Statements

Client Server

SELECT foo FROM barWHERE id = ?

•Query database

Resultset(s)

Handle

HandleParam 1: 42

•Create Execution plan

Page 24: 20110713 Webinar Mysql Php v1

Prepared Statements and mysqli

$query = "INSERT INTO employees (first_name, last_name, gender)VALUES (?,?,?)";

$stmt = mysqli_prepare($conn, $query);

mysqli_stmt_bind_param($stmt, "sss", $val1, $val2, $val3);

$val1 = 'Ulf';$val2 = 'Wendel';$val3 = 'M';mysqli_stmt_execute($stmt);

$val1 = 'Andrey';$val2 = 'Hristov';$val3 = 'M';mysqli_stmt_execute($stmt);

mysqli_stmt_close($stmt);

Page 25: 20110713 Webinar Mysql Php v1

PHP Extensions for MySQL

PDO_mysql

ext/mysql mysqli

PHP

Page 26: 20110713 Webinar Mysql Php v1

ext/mysql

• One of the first PHP extensions

• Actively maintained with PHP 4

– No new features in PHP 5

• Exception: Added mysqlnd support with PHP 5.3

– Bug fixing only

• Missing support for many MySQL features

– Prepared statements, Queries with multiple result sets (stored procedures), compression, encryption, full charset support, …

Page 27: 20110713 Webinar Mysql Php v1

mysqliThe Improved MySQL Extension

• Full support for all MySQL features

– Stored Procedures

– Prepared Statements

– Encryption (SSL)

– Compression

– Charsets

– …

• Actively developed, maintained and supported by Oracle

Page 28: 20110713 Webinar Mysql Php v1

PDO_mysql

• “The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP.” http://php.net/intro.pdo

• Lowest common denominator

• PHPish API

• PDO is emulating prepared statements by default$pdo->setOption(PDO::MYSQL_ATTR_DIRECT_QUERY, false);

Page 29: 20110713 Webinar Mysql Php v1

PDO

<?php

$pdo = new

PDO(“mysql:host=localhost;dbname=test”,

“user”, “password”);

$query = $pdo->prepare(

“SELECT id FROM table LIMT ?, ?”);

$query->bindValue(1, $_GET[“offset”]);

$query->bindValue(2, $_GET[“limit”]);

$query->execute();

Page 30: 20110713 Webinar Mysql Php v1

PDO

<?php

$pdo = new

PDO(“mysql:host=localhost;dbname=test”,

“user”, “password”);

$query = $pdo->prepare(

“SELECT id FROM table LIMT ?, ?”);

$query->bindValue(1, $_GET[“offset”]);

$query->bindValue(2, $_GET[“limit”]);

$query->execute();1064 You have an error in your SQL syntax; check themanual that corresponds to your MySQL server versionfor the right syntax to use near ''1', '2''

Page 31: 20110713 Webinar Mysql Php v1

PDO

SELECT id FROM table LIMT ?, ?

$_GET[“offset”] $_GET[“limit”]

SELECT id FROM table LIMT '1', '2'

Page 32: 20110713 Webinar Mysql Php v1

PDO

<?php

$pdo = new

PDO(“mysql:host=localhost;dbname=test”,

“user”, “password”);

$query = $pdo->prepare(

“SELECT id FROM table LIMT ?, ?”);

$query->bindValue(1, $_GET[“offset”],

PDO::PARAM_INT);

$query->bindValue(2, (int) $_GET[“limit”]);

$query->execute();

Page 33: 20110713 Webinar Mysql Php v1

Reasons for using different APIs

• mysqli

– Support for all MySQL features

– Best support / stability

– Integration with existing applications / environments

• PDO

– Simple applications supporting multiple databases (for instance Oracle DB and MySQL)

– Integration with existing applications / environments

Page 34: 20110713 Webinar Mysql Php v1

<Insert Picture Here>

PHP Frameworks

Page 35: 20110713 Webinar Mysql Php v1

Frameworks

• PHP applications often have to do the same things over and over again

– Handling navigation

– Handling form data

• There are proven concepts for application architectures

– Model-View-Controller

Frameworks usually safe time and enforce clean structures

Page 36: 20110713 Webinar Mysql Php v1

Frameworks

• There are two major general purpose frameworks

– Zend Framework

• Zend Technologies, Ltd.

• http://framework.zend.com

– Symfony

• Sensio Labs

• http://www.symfony-project.org

– Others include: CakePHP, Agavi, Zeta Components

• Many applications provide their own framework

– Typo3, Drupal, Joomla

Page 37: 20110713 Webinar Mysql Php v1

Database Abstraction Layers – Doctrine 2

namespace MyApp {

/** @Entity @Table(name="employees") */

class Employee {

/** @Id @Column(type="integer") @GenerateValue */

private $id;

/** @Column(length=50) */

private $lastName;

public function setLastName($name) {

$this->lastName = $name;

}

}

}

Page 38: 20110713 Webinar Mysql Php v1

Database Abstraction Layers – Doctrine 2

$connectionOptions = array(

'driver' => 'pdo_mysql',

/*...*/

);

$em = EntityManager::create($connectionOptions, $config);

$user = new User;

$user->setName('Smith');

$em->persist($user);

$em->flush();

$q = $em->createQuery('SELECT e FROM MyApp\Employee e');

$users = $q->execute();

Page 39: 20110713 Webinar Mysql Php v1

<Insert Picture Here>

Looking Deeper Into PHP

Page 40: 20110713 Webinar Mysql Php v1

PHP 5.3 and mysqlndP

HP

PH

P M

em

ory

PH

P S

tream

sInfrastructure

mysqlnd – MySQL native driver for PHP

MySQL Server

ext/mysql mysqli PDO_mysql

…PHP Module (Extension) API

Page 41: 20110713 Webinar Mysql Php v1

mysqlnd Statistics

• Around 150 statistic values collected

• mysqli_get_client_stats(), mysqli_get_connection_stats()

Page 42: 20110713 Webinar Mysql Php v1

Asynchronous QueriesPHP

ScriptMySQL

query

result

Page 43: 20110713 Webinar Mysql Php v1

Asynchronous Queries

/* Do something */

PHP Script

MySQL

query

result

query

poll

result

$conn = new MySQLi(...);

$conn->query("SELECT * FROM t WHERE ....",

MYSQLI_ASYNC);

/* Process query results */

mysqli_poll($links, $errors, $reject, 1);

Page 44: 20110713 Webinar Mysql Php v1

Learning More

Two more Webinars coming up:

1)Best practice API usage

2)How mysqlnd plugins help you to scale

Page 46: 20110713 Webinar Mysql Php v1

The preceding is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.

Page 47: 20110713 Webinar Mysql Php v1

<Insert Picture Here>

Thank You!

Johannes Schlü[email protected]

Wei-Chen [email protected]

Page 48: 20110713 Webinar Mysql Php v1

Recommended