Date post: | 06-Mar-2015 |
Category: |
Documents |
Upload: | pushpasrinivasan |
View: | 35 times |
Download: | 1 times |
<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
© 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
© 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
© 2011 Oracle Corporation – Proprietary and Confidential
MySQL Powers the Web
Enterprise 2.0SaaS, Hosting
Web OEM / ISV’s
Telecommunication
s
MySQL Customers
<Insert Picture Here>
Johannes SchlüterMySQL Engineering: Connectors & Client Connectivity
Building High Performance and High Traffic PHP Applications with MySQL - Part 1: The Fundamentals
<Insert Picture Here>
Introduction And Installation
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
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
XAMPP
www.apachefriends.org/xampp
IDE – NetBeans – www.netbeans.org
Verifying the PHP Installation
c:\xampp\htdocs\test.php:
<?phpphpinfo();?>
http://localhost/test.php
MySQL Workbench
<Insert Picture Here>
Getting Started
<?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
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>
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!
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!”);
}?>
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.
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}
Prepared Statements
Client Server
SELECT foo FROM barWHERE id = 42
•Create Execution plan•Query database
Resultset(s)
Prepared Statements
Client Server
SELECT foo FROM barWHERE id = ?
Handle
•Create Execution plan
Prepared Statements
Client Server
SELECT foo FROM barWHERE id = ?
•Query database
Resultset(s)
Handle
HandleParam 1: 42
•Create Execution plan
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);
PHP Extensions for MySQL
PDO_mysql
ext/mysql mysqli
PHP
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, …
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
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);
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();
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''
PDO
SELECT id FROM table LIMT ?, ?
$_GET[“offset”] $_GET[“limit”]
SELECT id FROM table LIMT '1', '2'
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();
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
<Insert Picture Here>
PHP Frameworks
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
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
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;
}
}
}
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();
<Insert Picture Here>
Looking Deeper Into PHP
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
mysqlnd Statistics
• Around 150 statistic values collected
• mysqli_get_client_stats(), mysqli_get_connection_stats()
Asynchronous QueriesPHP
ScriptMySQL
query
result
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);
Learning More
Two more Webinars coming up:
1)Best practice API usage
2)How mysqlnd plugins help you to scale
• Use MySQL with PHPhttp://dev.mysql.com/usingmysql/php/
• Read Connector/PHP User Manualhttp://dev.mysql.com/doc/refman/5.1/en/apis-php.html
• Download Free MySQL White Papershttp://dev.mysql.com/why-mysql/white-papers/
• View MySQL Training Courses http://www.oracle.com/education/mysql
• Follow MySQL Updates on Facebookhttp://www.facebook.com/mysql
Learn More: Resources
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.