We all know that an SQL query will either execute completely or not at all (i.e. they are atoms). But, sometimes, we want several queries to be bundled together as response to business logic. Transaction processing will help you to ensure this and maintain database integrity.
If you are new to MySQL transaction with PHP, then this article will definitely help. :-)
Step One - Make sure the type of your database table is innoDB not MyISAM.
(Here is a screenshot of from phpMyAdmin)Step Two - Start transaction $dbh->query('BEGIN');
$dbh is an pearDB object ($dbh = new pearDB(), if you are not familiar with pearDB, please click here.)
Step Three - Specify your queries which reflect the business logic. ($sqlA and $sqlB)
Step Four - 'ROLLBACK' to cancel $sqlA and $sqlB, and 'COMMIT' to confirm the changes.
Code Example:
(Click the image to Enlarge)
If you have any question or suggestion, feel free contact me on twitter: http://twitter.com/alexzang
Wednesday, 12 September 2007
MySQL Transaction in PHP (Commit & Rollback)
Posted by
Alex Zang
at
7:31 pm
Labels: MySQL, PHP, Sample Code, Tutorial
Saturday, 8 September 2007
AJAX & Web 2.0 Tutorial (Section 5) - Debug & Performance
1. AJAX applications don’t exist in a vacuum, while much of the code can reside on the client, the essence of AJAX applications is the interaction with the server, which necessarily involves load.
2. Debugging AJAX applications can be challenging for a couple reasons, including:
- Browsers suck
- Multiple languages involved
- Development environment probably doesn’t support debuging PHP & JavaScript
- Communication between client and server may notbe visible
3. Debugging Tools
- Firebug - Firefox Extension
(Supports step by step debugging, breakpoints and watches; Handles multiple JavaScript documents concurrently; Gives you somewhat nicer error messages)
- Ethereal/Wireshark (Industry standard tool for packet sniffing)
-Live HTTP Headers and HTTP Inspector
(built into Komondo, acts as a proxy for requests)
-Yahoo! Logger library (YAHOO.log)
Friday, 7 September 2007
AJAX & Web 2.0 Tutorial (Section 5) - Applications
- If you ask someone what Ajax stands for, they might answer it doesn’t stand for anything, or they might say “Asynchronous JavaScript And XML”
- Asynchronous means that you’re welcome to send requests one after another, but they’re not guaranteed to return in that order (really, they’re not guaranteed to return at all, but that’s rare)
- Server load affects your scripts in two similarbut different ways, including:
- Everything gets slower
- Different parts of things get slower (So some scripts that originally took similar amounts of time can now take drastically different amounts of time)
- While Ajax encourages more communication between client and server, it’s generally the same information you would provide anyways, developers simply need to maintain their normal level of vigilance.
- There are many situations within Ajax applications where this is sub-optimal
- A user could enter invalid login credentials, then hit the login button. Realize their mistake correct it then hit it again
- Select something from a list to have further information populated by Ajax, then select another item
- A user could click a button to login, then activate another page element that requires them to have logged in before access
Thursday, 6 September 2007
AJAX & Web 2.0 Tutorial (Section 4) - Yahoo User Interface (YUI )
- The Yahoo! User Interface Library is a set of utilities and controls that make your life easier;
- They’re released under a BSD style license;
- Apart from solving cross browser problems, the library also includes code to do a lot of nifty things;
- The library is available at http://developer.yahoo.com/yui/
- Please go download the library and set it up in your development environment; :-)
- Auto Complete is one of those nice finishing touches that can make most websites just seem better. It’s also a perfect case of supplementing the user experience, rather than providing it, worst case scenario the user doesn’t receivethe drop down.
Sample Code:
<script type="text/javascript">
YAHOO.example.ACFlatData = function(){
var mylogger;
var oACDS;
var oAutoComp0,oAutoComp1,oAutoComp2;
return {
init: function() {
mylogger = new YAHOO.widget.LogReader("logger");
oACDS = new YAHOO.widget.DS_XHR("./sampleAutoComplete.php", ["\n", "\t"]);
oACDS.responseType = YAHOO.widget.DS_XHR.TYPE_FLAT;
oACDS.maxCacheEntries = 60;
oACDS.queryMatchSubset = true;
oAutoComp2 = new YAHOO.widget.AutoComplete
('ysearchinput2','ysearchcontainer2', oACDS);
oAutoComp2.delimChar = ";";
oAutoComp2.queryDelay = 0;
oAutoComp2.prehighlightClassName = "yui-ac-prehighlight";
},
validateForm: function() {
return false;
}
};
}();
YAHOO.util.Event.addListener(this,'load',YAHOO.example.ACFlatData.init);
</script>
Wednesday, 5 September 2007
AJAX & Web 2.0 Tutorial (Section 3) - JSON
- JSON (JavaScript Object Notation) is a subset of how objects are represented in JavaScript
- It’s presented as a lightweight information transfer protocol, similar in many respects to XML
- What makes JSON useful in JavaScript is that it can be parsed very easily (eval())JSON can contain any number of elements, nested key value pairs, objects, arrays, etc.
- Until a library is introduced the easiest way to transfer data between your script and PHP is to use simple GET & POST based requests for transmission, and JSON for receipt.
- Different browsers interpret JavaScript differently, IE in particular goes off in its own direction (xmlHTTP request works differently, it’s difficult to re-use ajax objects, data is stored in linked lists rather than a hash table so it’s notably slower)
- You could do some serious research, understand all the little differences, and write your code appropriately, or...
JSON Example:
<script type="text/javascript">
var name = "alex";
httpRequest = new XMLHttpRequest();
httpRequest.open('GET', 'http://localtest.luxplus.net/alfa/
ucase.php?text=' + name);
httpRequest.onreadystatechange = function()
{
if (httpRequest.readyState == 4)
{
responseJSON = eval("(" + httpRequest.responseText + ")");
alert(responseJSON.ucase);
}
}
httpRequest.send(null);
</script>
/* ucase.php */
<?php
$string = isset($_GET['text']) ? strtoupper($_GET['text']) :
strtoupper("default");
$data['ucase'] = $string;
$returnValue = json_encode($data);
echo $returnValue;
?>
Posted by
Alex Zang
at
10:15 pm
Labels: AJAX, Sample Code, Tutorial
AJAX & Web 2.0 Tutorial (Section 2) - Web Services
- Web Services are a way for disparate applications to work with each other over the web;
- In order for different applications to communicate with each other they need to agree on a protocol, webservices have three common protocols, JavaScript throws a fourth into the mix;
- REST - Simple request protocol, looks identical to a form being filled out, response is a basic XML document;
- XML-RPC - XML request-response protocol, format chosen is sub-optimal for parsing with DOM tools;
- SOAP - Heavy but well defined XML based request-response protocol;
- JSON - JavaScript Object Notation - information is passed back and forth in the JavaScript notation;
- Ditch SOAP & XML-RPC, (SOAP is too heavy for frequent small requests, XML-RPC is just ugly);
- REST - Light weight requests, some basic frameworks are available. Define your own response XML format;
- JSON - The JSON format is relatively lightweight but still ‘new’ enough that it’s not too widely supported (JSON support was added in PHP 5.2.0);
- It’s critical to remember that HTTP is a stateless protocol, every request must stand alone, independent of each other request. While technologies like sessions help can help when dealing with end users, they are inappropriate when using web services;
- When developing web services leverage and re-factor existing code, rather than duplicating;
- Objects are rather... different compared to other languages. Rather than defining a specific
class, than instantiating instances of it, objects are created from functions that pull in their own required methods. This can be done on the fly, or by defining functions inside other functions.
Posted by
Alex Zang
at
6:18 pm
Labels: AJAX, Javascript, Tutorial
Tuesday, 4 September 2007
AJAX & Web 2.0 Tutorial (Section 1) - Javascript Basics
- Javascript has nothing to do with Java.
- Javascript is a client side language, it is executed by the browser, not the server.
- Javascript can be used to manipulate HTML documents, this allows the programmer to do all sort of nifty things. (Like AJAX)
- Creating Valid HTML documents is the first step to giving yourself an easier JavaScript existence, things will start working sooner, and generally break in more predictable and understandable ways.
- Many developers new to JavaScript look at the source code of their application to look for output, which seems like it should hold the answer, it doesn’t. When you modify the document using JavaScript you’re modifying the document in memory, the source doesn’t
actually change. - Proper code needs a finished document with which to work, store your initialization code inside a function called in the body tag’s onload event. It’s good practice to encapsulate
your code within a function anyways. - JavaScript variables are very similar to PHP
- Loosely Typed
- Number - Floating point number, stored internally using 64bit representation
- Boolean - true or false
- Strings - Encapsulated within quotes (no heredoc)
- Objects
- Best way to convert text into a number is by using the Number() function, if it runs into a problem it will return produce.
- To convert a value into an Integer use the parseInt(value, base) function. It accepts both
the object containing the value you wish to convert, and the base at which the conversion should take place (avoiding those silly issues with leading zeros)
Saturday, 1 September 2007
MySQL DB Design Tutorial (Section 4) - Naming Suffixed
This list of postfixes for data element names based on the ISO-11179 Standard
- _id = Identifier, it is unique in the schema and refer to one entity anywhere it appears in the schema.
- _data or dt = date, temporal dimension.
- _nbr or num = tag number; this is a string of digits that names something.
- _name or nm = this is an alphabetic name and it explains itself.
- _code or _cd = A code is a standard maintained by a trusted source, usually outside of the enterprise.
- _size = an industry standard or company scale for a commodity, such as clothing, shoes, envelopes or machine screws.
- _tot = sum, an aggregated dimension which is logically different from its parts.
- _seq = a sequential numbering.
- _tally = a count of values.
- _cat = Category
- _cls or _class = a class
- _type = an encoding that has a common meaning both internally and externally.
- The differences among type, class, and category are an increasing strength of the algorithm for assigning the type, class, or category.
- The thress terms are often mixed in actual usage.
- _status = an internal encoding that reflects a state of being.
- _addr or _loc = An address or location for an entity.
- _img = An image data type, such as .jpg, .gif, .gif and so forth.
MySQL DB Design Tutorial (Section 3) - Column Constraints & Database Relationships
The following are the list of constraints that can be assigned to columns in MySQL:
- Not NULL | NULL (Default vallue) - Primary key (implied)
- DEFAULT - Not available in BLOG/TEXT; AUTO_INCREMENT; NULL Values
- UNIQUE
Database Relationships
- One-to-One (1:1) is when at most one instance of a entity A is associated with one instance of entity B.
- One-to-Many (1:N) relationships is when for one instance of entity A, there are zero, one, or many instances of entity B, but for one instance of entity B, there is only one instance of entity A.
- Many-to-Many (M:N) relationship is when for one instance of entity A, there are zero, one, or many instances of entity B and for one instance of entity B there are zero, one, or many instances of entity A.
Friday, 31 August 2007
MySQL DB Design Tutorial (Section 2) - Database Components
The following are a list of the more common table types that will be used in designing a database:
- Stage Tables (Raw data in SQL, to be scrubbed), Base tables, Auxiliary tables, Archival tables (for data warehouse), Audit tables (for recovery and layers) and virtual tables (views, derived tables, CTE)
- Measurement Encoding (a measurement encoding is given in some unit of measure, such as pounds, volts or liters) can be done in one of two ways: A. The column contains an implied unit of measure and the numbers represent the quantity in that unit; B. The column explicitly contains the unit.
- Abbreviation Encoding (Abbreviation codes shorten the attribute values to fit into less storate space, but the reader easily understands them) is very handy, but as the set of values becomes larger, the possibility for misunderstanding increases. Example: Consider the ISO 3166 Country Codes, which come in two-letter, three-letter and non-abbreviation numeric forms.
- Algorithmic Encoding (Algorithmic encoding takes the value to be encoded and puts it through an algorithm to obtain the encodings). Example: Encription is the most common example of an algorithmic encoding scheme.
- Hierarchical Encoding (A hierarchy partitions the set of values into disjoint categories, then partitions those categories into subcategories, and so forth until some final level is reached). Example: The most common example is the ZIP code, which partitions the US geographically.
Define Encoding Schemes In MySQL
- col_name {CHAR | VARCHAR} (col_length) [CHARACTER SET charset_name] [COLLATE collation_name]
MySQL DB Design Tutorial (Section 1) - Introductions
Ratio Scales (Ratio scales are what people think of when they think about a measurement)
- Ratio scales have an origin, an ordering, and a set of operations that can be expressed in arithmetic.
- They are called ratio scales because all measurements are expressed as multiples of fractions of a certain unit or interval.
- Examples: length, mass, and volume. (The unit is what is arbitrary; the weight of a bag of sand is still weight whether it is measured in kilograms or in pounds)
- Make sure that each table in your database has been reviewed for possible relationships with other tables.
- For tables with relationships to other tables, make sure that the relationship has been properly identified. This would include: A. The type of participation between the tables; B. The degree of participation between the tables.
- Make certain that each foreign key meets the following best practice suggestions: A. The name of the foreign key should match the name of the primary key it is related to (a data element has only one and only one name in a schema); B. The column specifications of the foreign key are identical to those of the primary key.
- This level of integrity is a vital aspect of database design and the following lists some of the more important terms associated with integrity: A. Column Specification (general elements, physical elements, and logical elements); B. Data Integrity (table-level, column-level, and referential integrity)
Monday, 27 August 2007
PHP Basics (Section 5) - Object Oriented Programming
1. Prior to PHP5 OOP was a hack on top of the array implementation.
2. PHP5 changed eveything, in a great way.
3. Simple OO Example:
class person
{
public $age;
public $name;
function __construct($name, $age)
{
$this->name = $name;
$this->age = $age;
}
function birthday()
{
echo "Happy Birthday " . $this->name . "!";
$this->age++;
}
}
4. Public - Method or property can be accessed externally.
5. Private - Method or property is private to that class and can not be accessed externally.
6. Protected - Method or property is private and can also be accessed by extending classes
7. Final - Method can be overridden by extending classes.
8. Extending Example:
class friend extends person
{
private $relationship;
const MYNAME = "paul";
function __construct($name, $age, $relationship)
{
parent::__construct($name, $age);
$this->relationship = $relationship;
}
function showStatus()
{
echo "{$this->name} is my {$this->relationship}";
}
function fight()
{
$this->relationship = "enemy";
}
static function phoneCall()
{
echo friend::MYNAME . " the phone is for you";
}
9. Autoloading Example:
function __autoload($class_name)
{
require_once "/www/phpClasses/
{$class_name}.inc.php";
}
$a = new friend;
10. Special Functions: __construct(), __destruct(), __toString(), __sleep() __wakeup(), __call(), __get(), __set()
11. Design Patterns - Some time ago people realized that we were solving the same problems again and again, they then decided to sit down and come up with really good solutions to those problems, they’re called design patterns.
12. The advantages of design patterns are two fold: first they present a well defined solution to common problems, second they provide a common language for developers.
Posted by
Alex Zang
at
11:28 am
Labels: PHP, Sample Code, Tutorial
Sunday, 26 August 2007
PHP Basics (Section 4) - Files
- Files provide a simple temporary to permanent data store.
- PHP5 presents two functions which make handling files, namely file_get_contents() and file_put_contents().
- For large amounts of data, or in issues where a race condition is possible a database would be a better data store.
- Steams are the way that PHP handles working with network resources.
- Whenever you open up a file PHP creates a stream in the background.
- Each stream consists of several components: file wrapper, one or two pipe-lines, an optional context, metadata about the stream.
- Files can be locked to prevent race conditions:
flock($fp, LOCK_SH); //Place Shared lock
flock($fp, LOCK_EX); //
Place Exclusive (write) Lock
flock($fp, LOCK_UN); //Release lock - Placing and removing locks can inhibit performance as traffic increases, consider using a different data store.
- Using stream context and a few other techniques a lot can be done without resorting to sockets, however for more detailed control sockets can be used.
- Sockets allow read/write access to various socket connections, while things like HTTP may seem read only, at the protocol level information is being sent to identify the desired resource. Example:
$fp = fsockopen
("example.preinheimer.com", 80, $errno, $errstr, 30)
;
if (!$fp) {
echo "$errstr ($errno)\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: example.preinheimer.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}
Saturday, 25 August 2007
PHP Basics (Section 3) - Security
Defense in Depth
- When you plan with defense in depth, you plan for failure. Rather than internal functions assuming the data they receive is already validated or escaped, they will check and confirm.
- Application that demonstrate defense in depth are not noly more resistant to attack when they are developed, they also remain more resistant over time as new attacks are developed, and as more code is added to them.
- Your PHP applications by default has a lot of power, they execute as the web user (often apache or www-data) with all the rights and privileges thereof.
- If an attacker gains control of PHP through an application vulnerability this can be used and abused.
- These terms are often confused, or used interchangeably.
- Validation or Filtering is the process by which you subject data to a series of rules, either it passes (validates) or does not.
- Escaping is the process by which you prepare data for a specific resource by "escaping" certain portions of the data to avoid confusion of instruction and data.
- Whenever you receive data one of three things can be said about it: 1) It is valid, the user entered the data you want, in the format you desire; 2) It is invalid because the user either did not comply or did not understand the rules on the data you requested (eg. Poorly formatted postcode); 3) It is invalid because the user is attempting to compromise your application.
- Data from the end user can not be trusted, it must be validated before it can be used.
- Validate data first don't save it for last.
- Fail early, tell the user what went wrong.
- There are two major approaches to data validation, the whitelist and blacklist approach.
- Under the whitelist approach you select a series of valid characteristics (frequently characters) only data that follows these rules is accepted as valid.
- Under the blacklist approach you select a series of invalid characteristics, any data that contains these characteristics is considered invalid.
- Under a cross site scripting attack an attacker injects code into your page (forum post, shout box, etc) that contains code that re-writes the page to do something nefarious.
- This can be prevented through proper escaping and data validation techniques
- Under a cross site request forgery attack a site exploits another sites persistent user trust relationship to make something happen.
- iFrames are another common tool leveraged in this technique.
- Sessions provide safer state, it may not nesesarily be safe.
- Basically, sessions combine cookies containing a session ID with a local(ish) data store corresponding to that session id.
- If the session id is compromised, or the data store is not secure (/tmp on a shared machine) sessions are still vulnerable to attack.
- Session IDs are very random.
- Predicting them is hard, it’s much easier to: 1) Check out /tmp on a shared server, see what people have; 2)Intercept communications; 3)Implement session fixation.
- To defend, implement some browser fingerprinting.
Friday, 24 August 2007
PHP Basics (Section 2) - Functions & String
Function
- We use functions for several major reasons: readability, code separation, maintainability, modularity.
- In PHP4 objects were thrown around ByVal, this meant that you made copies without even thinking about it.
- In PHP5 objects are always passed BrRef unless you explicitly clone it, keep that in mind.
- Return statements can exist anywhere anywhere within the function, and you can even have multiple return values.
- Avoid situations where the same function may return nothing, or something.
- Strings are the most commonly used variable type in PHP, because they are both central to web development, and the common method of data transmission from the user
- Within strings many characters take a special meaning, matching quotes, back slashes, octal numbers, variables, if you wish to accept them as they are you mush escape them with the \ character.
- strcmp() - Compare two strings. Returns > 0 if $string_1 is greater than $string_2, and 0 if they are equal.
- strcasecrm() - Case insensitive version of strcmp()
- substr() - Used to retrieve a portion of a string
- number_format() - By default formats a number with the comma as the thousands separator, and no decimal.
- preg_match() - Returns the number of matches found by a given search string under this format, also capable of returning the match.
echo number_format("1234567.123"); //Shows 1,234,567
echo number_format("1234567.123", 3, ",", " "); //Shows 1 234 567.123
$string = "156 abc";
var_dump(preg_match("/\w\s\w/", $string)); // 1 (matches)
PHP Basics (Section 1) - Database
I'd like to blog my understanding of PHP based on my 10+ years experience in developing scalable web based applications. There will be 14 sections in total, including: database, functions, strings, security, design pattern, javascript and more... :-) Here is the first section --- DATABASE
- Database cannot be tested by using specific code.
- While PHP is loosely types, databases are not. Therefore, detailed Information about the data being stored is required for efficient storage and retrieval, common data-types include: int(signed integer number, 32bits), char(fixed length character string), varchar(variable length character string), float(signed floating point number, 64bits)
- Most modern database systems fall into the relational category, the basis of which is the relationship between various tables
- Relationships link records based on some common data, relationships can be one to one, one to many, many to many
- DB systems can be configured to enforce those relationships to maintain referential integrity
- DB are smart and fast, but the DB designer has foreknowledge of how the DB will be used
- With this knowledge the designer can create an index on appropriate columns
- This index instructs the DBMS to store additional information about the data in that column, to make locating data within it as fast as possible
- Transactions allow you to merge multiple queries into one atomic operation, either they ALL execute successfully, or none do. (BEGIN TRANSACTION #name; ...queries here, COMMIT;) - Transactions are only available on InnoDB. :-)