Go Premium for a chance to win a PS4. Enter to Win

x

Web Applications

14K

Solutions

14K

Contributors

Web applications are systems that run in browsers that perform functions normally associated with other client-based programs. One of the most commonly used web applications is email; instead of downloading individual emails to a local machine, the data is shown through a website. Other examples of web applications are collaborative systems like a wiki or an online game.

Share tech news, updates, or what's on your mind.

Sign up to Post

Introduction
HyperText Transfer Protocol or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to the WWW in the days after 2005 (and therefore after the advent of jQuery), that seem to evince a misunderstanding of the way the HTTP protocol works.  Since HTTP is the basic building block of web sites and web applications, a clear understanding of the protocol is required to understand how web sites really work.  And perhaps more importantly, it is necessary to understand the protocol so you can build a web site that works like another site you've seen and appreciated.  This article is intended to lift the cloud of confusion that has appeared in the years since the arrival of jQuery, CSS3, animation in web sites, and the phenomenon called Web 2.0.

The confusion has arisen in large measure because of the design movement of web interactivity away from the static page loads and into design paradigms that more closely mimic native applications.  If the hyperlink was the design element that launched the internet revolution, the event handler may be thought of as the design element that has most refined the client experience.  In all cases, at the foundation is the HTTP protocol.

HTTP is a Stateless Client/Server Protocol
Client/Server protocols are two-way communication mechanisms that allow humans to get information from web sites
19
 
LVL 15

Expert Comment

by:Eric AKA Netminder
Comment Utility
Ray,

A typically outstanding article. I've been fumbling through telling people this stuff for a long time, so it's nice to have a clear resource to which to send them.

Thanks!

ep
0

Introduction (All good things must come to an end)mysql_warning.pngThe original MySQL API has gone away.  It was deprecated (years ago) by PHP in Version 5.5, and removed from PHP in all current releases.  As a result, the issue is upon us today.  It's time to remediate our old PHP scripts, and bring them up-to-date for the current millennium. This article explains the issues and gives step-by-step and line-by-line instructions that can lead us out of the MySQL darkness and into current best practices.


WHY in the World Did PHP Do This?

Great question!  The MySQL extension was by far the most popular data base extension used by PHP web sites.  It had good documentation and support (consider phpMyAdmin, and after you've used that, go over to phpPgAdmin and compare features).  MySQL was thoroughly debugged, and was widely accessible - you could find literally thousands of examples of PHP+MySQL code with a Google search.  So why did PHP take such a draconian step?  In my opinion, it comes down to two issues.  


First, PHP has "grown up" as a programming language.  At one time, its proponents were looked down upon as script kiddies by the computer science community.  Never mind the fact that parts of Google, much of Yahoo, and nearly all of Facebook, Digg, Wikipedia, WordPress, and Slack are PHP machines -- there was a stench is created by the millions of incompetently written PHP web sites that crashed and got hacked all the time.  It's very easy to pick up a little knowledge about PHP and MySQL, and an unfortunate corollary is that it's very easy to use PHP and MySQL wrong!  Security holes abound, and the unsophisticated programmer propagates these errors by copying PHP code without understanding the dangers.  So in an effort to bring some rigor and science to the creation of PHP scripts, we got this explanation from P. Olson.  As you might imagine, there was early controversy over the change, but that is in the past now.


Second, the PHP authors were actually right -- the MySQL extension was simply terrible about security.  If it had been any good, there wouldn't have been a need for two million MySQL security articles!  There was nothing inherently wrong in the extension; the trouble came from the way novice programmers misused the extension.  As but one example, consider the use of external data in MySQL queries.  A common-sense implementation would have prevented the use of a query variable that had not been escaped.  But the original implementation of the MySQL extension imposed no such requirement, and the resulting security holes caused many web sites to fail. 


PHP tried to discourage the use of the MySQL extension at PHP 5.0 by removing the MySQL extension from the standard installation.  But that did not have the desired effect of luring programmers away from the dangerous and sloppy code, and that was done more than 10 years ago.  So a bigger stick was needed. The only way to make such a sweeping change in the behavior of a language interpreter (and a huge population of users) was to remove the dangerous parts of PHP and force programmers to stop using them.


In addition to security, there are many good reasons to adopt object-oriented programming techniques.  The MySQL extension by its very nature, frustrated this effort.  The MySQL API was procedural, leading to code that was messy, difficult to maintain and impossible to reuse.  In contrast, the MySQLi and PDO extensions offer object-oriented interfaces.


What are Others Saying and Doing About This Change?

On April 7, 2014, the Make WordPress team issued this announcement:

In WordPress 3.9, we added an extra layer to WPDB, causing it to switch to using the mysqli PHP library, when using PHP 5.5 or higher.  For plugin developers, this means that you absolutely shouldn’t be using PHP's mysql_*() functions any more - you can use the equivalent WPDB functions instead.


OK, What Should I Do?

First, adopt a coding standard that prohibits further use of the MySQL extension.  After today, you must never write mysql_query() again! Next, learn about the alternatives to MySQL.  Basically, you've got two good choices: MySQLi or PHP Data Objects ("PDO").


Second, be aware of the environmental changes that accompany this PHP change.  Installation libraries are different now.  The way you install the MySQL extensions is different now.  Please take a moment to read this page, especially if you're moving from an obsolete PHP 5.3 installation to a current release or version!

https://dev.mysql.com/downloads/connector/php-mysqlnd/


Do I Have to Change my PHP Programs?

Yes.  And the rest of this article shows annotated code examples to help you understand how to accomplish the changes.  The scripts have been set up as teaching examples.  You should be able to add your own MySQL credentials and install them on your own servers.  Then you can run them to see how the scripts work and how the output from error messages differs.


The scripts are shown in complete form at the bottom of the article.  In the annotated parts, only the essential pieces are shown to illustrate the different approaches.  


In each code set, the first example is the familiar-but-obsolete MySQL extension.  Following that, we have the MySQLi extension.  In that example, I tried to aim for the most direct one-to-one replacement of existing MySQL programming.  Of necessity this meant avoiding MySQLi prepared statements.  They are introduced in the PDO example, and a complete MySQLi example showing the use of prepared statements is included with the code snippets at the end of the article.  There are some differences in the syntax but for the most part the functionality lines up 1:1 between MySQL and MySQLi.  That cannot be said for PDO, where some substantial programming changes come into play.


MySQLi or PDO?

Which extensions should you choose?  Either will work.  Object-oriented MySQLi requires the smallest number of code changes.  PDO holds out the promise that you could, theoretically, change out the underlying data base without having to change your PHP scripts.  I don't know any professional programmer who believes such a claim, given the variations in SQL.  And PDO can only give you parameter binding if you use prepared statements, thus introducing a good bit of overhead.  Your choice will largely depend on the amount of time you want devote to the required modifications.  Can you trust your programmers to remember to escape external data before using it in a query?  If the answer is "yes" then MySQLi is a good choice, even if many computer scientists would express a preference for PDO.  


If you are considering PDO, this article is worth reading, but be aware that there are errors in the article's code examples.  Read for comprehension, but don't copy the code unless you're willing to do some debugging!


Object-Oriented or Procedural?

Object-oriented.  There are no real advantages and many disadvantages if you get stuck in procedural database extensions.  So just don't do that.


From personal experience, here are the reasons why I choose object-oriented MySQLi.


1. There can be two simultaneous connections to the DB engine.  You do not have to convert all of the old MySQL code at once - you can convert it query-by-query.


2. There are almost no changes needed to the SQL query strings (in PDO almost every query string will have to change).


3. There is almost 100% 1:1 matching of functionality (in PDO some of the MySQL operations are lost, eg, data_seek() does not exist).


4. There are relatively few code changes needed.  If you were to choose procedural MySQLi instead of OOP MySQLi, every call to the query() function would have to change because the procedural version requires the database link identifier as the first argument.  The OOP version infers the database link from the MySQLi object.


5. Anybody who really believes that using PDO will somehow magically let you change out the underlying data base engine, without creating havoc in your application software, has never tried to change out an underlying data base engine.


Do I Have to Change my Query Strings?

Probably not if you choose MySQLi.  Your queries require very modest changes (if any) when you choose the MySQLi extension.  PDO is a different story.  It uses an entirely different query structure with prepared statements and bound data.  PDO does not put PHP variables into its query strings; it passes the variables separately and thus it requires changes in almost all query strings, as well as the attendant PHP programming.  


Do I Have to Change my Data Base Tables?

No.  We are changing the API extensions, but we are not changing the underlying data base tables or the essential nature of the SQL query language.


This Sounds Like a Huge Amount of Work

Yes.  You almost certainly want to use some kind of version control.  But it does not have to be a daunting "all-or-nothing" task.  You can make simultaneous connections to the MySQL server using MySQLi alongside existing MySQL API code, in the same PHP script, and you can change your queries one at a time.  I have not tested it, but I would expect that the same might be true for PDO.


What Will I Learn Here?

Each of these examples performs the same basic data base functions.  We connect to the server and select a data base, we CREATE a table and load it with data.  We run a SELECT query and count the results.  We show the results set (using two methods of access to the rows of the results set).  We DELETE a row from the table.  And finally we run a query that is designed to fail so that we can see the differences in the error output.  You can print out these three scripts and follow the logic as you read the annotation and watch them run.


Man Page References

You will need to read these online references to understand the code in the snippets below.  No excuses, just do it.  You might even want to bookmark the PHP man pages. You may also want to review this web page that provides a map of MySQL functions to the MySQLi and PDO extensions.



MySQL

// THE ABSOLUTE MINIMUM YOU MUST UNDERSTAND TO USE PHP AND MYSQL
                                        // MAN PAGE: http://php.net/manual/en/ref.mysql.php
                                        // MAN PAGE: http://php.net/manual/en/mysql.installation.php
                                        // MAN PAGE: http://php.net/manual/en/function.mysql-connect.php
                                        // MAN PAGE: http://php.net/manual/en/function.mysql-select-db.php
                                        // MAN PAGE: http://php.net/manual/en/function.mysql-real-escape-string.php
                                        // MAN PAGE: http://php.net/manual/en/function.mysql-query.php
                                        // MAN PAGE: http://php.net/manual/en/function.mysql-errno.php
                                        // MAN PAGE: http://php.net/manual/en/function.mysql-error.php
                                        // MAN PAGE: http://php.net/manual/en/function.mysql-num-rows.php
                                        // MAN PAGE: http://php.net/manual/en/function.mysql-fetch-array.php
                                        // MAN PAGE: http://php.net/manual/en/function.mysql-fetch-assoc.php
                                        // MAN PAGE: http://php.net/manual/en/function.mysql-fetch-object.php
                                        // MAN PAGE: http://php.net/manual/en/function.mysql-insert-id.php

MySQLi


// THE ABSOLUTE MINIMUM YOU MUST UNDERSTAND TO USE PHP AND MYSQLI
                                        // MAN PAGE: http://php.net/manual/en/mysqli.overview.php
                                        // MAN PAGE: http://php.net/manual/en/class.mysqli.php
                                        // MAN PAGE: http://php.net/manual/en/class.mysqli-stmt.php
                                        // MAN PAGE: http://php.net/manual/en/class.mysqli-result.php
                                        // MAN PAGE: http://php.net/manual/en/class.mysqli-warning.php
                                        // MAN PAGE: http://php.net/manual/en/class.mysqli-sql-exception.php <-- DID NOT WORK PHP 5.3+, MySQL 5.1+
                                        // MAN PAGE: http://php.net/manual/en/mysqli.construct.php
                                        // MAN PAGE: http://php.net/manual/en/mysqli.real-escape-string.php
                                        // MAN PAGE: http://php.net/manual/en/mysqli.query.php
                                        // MAN PAGE: http://php.net/manual/en/mysqli.errno.php
                                        // MAN PAGE: http://php.net/manual/en/mysqli.error.php
                                        // MAN PAGE: http://php.net/manual/en/mysqli.insert-id.php
                                        // MAN PAGE: http://php.net/manual/en/mysqli-result.num-rows.php
                                        // MAN PAGE: http://php.net/manual/en/mysqli-result.fetch-array.php
                                        // MAN PAGE: http://php.net/manual/en/mysqli-result.fetch-object.php


PDO

// THE ABSOLUTE MINIMUM YOU MUST UNDERSTAND TO USE PHP AND PDO/MYSQL
                                        // MAN PAGE: http://php.net/manual/en/book.pdo.php
                                        // MAN PAGE: http://php.net/manual/en/class.pdo.php
                                        // MAN PAGE: http://php.net/manual/en/class.pdoexception.php
                                        // MAN PAGE: http://php.net/manual/en/class.pdostatement.php
                                        // MAN PAGE: http://php.net/manual/en/pdo.construct.php
                                        // MAN PAGE: http://php.net/manual/en/pdo.setattribute.php
                                        // MAN PAGE: http://php.net/manual/en/pdo.query.php
                                        // MAN PAGE: http://php.net/manual/en/pdo.prepare.php
                                        // MAN PAGE: http://php.net/manual/en/pdo.prepare.php#97942 <-- NO CURSOR SCROLLING
                                        // MAN PAGE: http://php.net/manual/en/pdostatement.execute.php
                                        // MAN PAGE: http://php.net/manual/en/pdo.lastinsertid.php
                                        // MAN PAGE: http://php.net/manual/en/pdostatement.bindparam.php
                                        // MAN PAGE: http://php.net/manual/en/pdostatement.rowcount.php
                                        // MAN PAGE: http://php.net/manual/en/pdostatement.fetchall.php
                                        // MAN PAGE: http://php.net/manual/en/pdostatement.fetchobject.php


Test Data

Identical for MySQL, MySQLi, and PDO.  It's the first thing you need if you're going to write computer programs.  In fact it's so important that a wise programmer will write the test data first, before a single line of code is laid!

 

// CREATE AN ARRAY OF NAMES TO USE FOR TEST DATA
                                        $test_names_arrays = array
                                        ( array( "fname" => "Walter" , "lname" => "Williams" )
                                        , array( "fname" => "Ray"    , "lname" => "Paseur"   )
                                        , array( "fname" => "Bill"   , "lname" => "O'Reilly" )
                                        , array( "fname" => "Ray"    , "lname" => "Capece"   )
                                        , array( "fname" => "John"   , "lname" => "Paseur"   )
                                        )
                                        ;


Authentication Credentials

Identical for MySQL, MySQLi, and PDO. Data base authentication credentials are the same for these extensions, however PDO uses the concept of a Data Source Name (combining the Data Base Engine and the Data Base Name).

 

// DATABASE CONNECTION AND SELECTION VARIABLES - GET THESE FROM YOUR HOSTING COMPANY
                                        $db_host = "localhost"; // PROBABLY THIS IS OK
                                        $db_name = "??";
                                        $db_user = "??";
                                        $db_word = "??";


Connect to the Server and Choose the Data Base

Each of these connections has very different information available in the DB connection resource or object.  For MySQL, the connection is a resource that does not tell us very much.  For MySQLi, the connection is an object with a rich collection of information.  For PDO, the connection is an object but it has no visible properties at this point.


MySQL uses connect and select function calls. Errors can be visualized using the appropriate error messages which can be found by calling the relevant MySQL functions.


MySQLi connects to the DB server by instantiation of a new MySQLi object. Errors, if any, can be found by visualizing the appropriate error messages which are properties of the MySQLi object.


Connect/select proceeds a bit differently in PDO.  Check the cautionary notes about accidental exposure of PDO authentication data. For this reason we wrap the instantiation of the PDO object in try/catch code blocks so we can handle the exceptions in our own code, rather than having an uncaught exception expose information that should not be made public.  More information on the PDOException object can be found in the online man pages.  PDO uses the Data Source Name ("DSN") that includes both the host name and the data base name.


MySQL

// OPEN A CONNECTION TO THE DATA BASE SERVER
                                        if (!$dbcon = mysql_connect("$db_host", "$db_user", "$db_word"))
                                        {
                                            $err
                                            = "NO DB CONNECTION: $db_host: "
                                            . mysql_errno()
                                            . ' '
                                            . mysql_error()
                                            ;
                                            trigger_error($err, E_USER_WARNING);
                                        }
                                        
                                        // SELECT THE MYSQL DATA BASE
                                        if (!mysql_select_db($db_name, $dbcon))
                                        {
                                            $err
                                            = "NO DB SELECTION: $db_name: "
                                            . mysql_errno()
                                            . ' '
                                            . mysql_error()
                                            ;
                                            trigger_error($err, E_USER_WARNING);
                                            trigger_error('NO DATABASE', E_USER_ERROR);
                                        }
                                        // SHOW WHAT THE DB CONNECTION LOOKS LIKE
                                        var_dump($dbcon);

  MySQLi


// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
                                        $mysqli = new mysqli($db_host, $db_user, $db_word, $db_name);
                                        
                                        // DID THE CONNECT/SELECT WORK OR FAIL?
                                        if ($mysqli->connect_errno)
                                        {
                                            $err
                                            = "CONNECT FAIL: "
                                            . $mysqli->connect_errno
                                            . ' '
                                            . $mysqli->connect_error
                                            ;
                                            trigger_error($err, E_USER_ERROR);
                                        }
                                        // SHOW WHAT THE DB CONNECTION OBJECT LOOKS LIKE
                                        var_dump($mysqli);


PDO

// WARNING: AN UNCAUGHT CONNECT ERROR WILL BARK OUT THE DB CREDENTIALS!
                                        // OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
                                        $dsn = "mysql:host=$db_host;dbname=$db_name";
                                        try
                                        {
                                            $pdo = new PDO($dsn, $db_user, $db_word);
                                        }
                                        catch(PDOException $exc)
                                        {
                                            var_dump($exc);
                                            trigger_error('NO PDO Connection', E_USER_ERROR);
                                        }
                                        // SHOW THE PDO CONNECTION OBJECT
                                        var_dump($pdo);


PDO - Error Visualization

This sets the attributes of the PDO object to control what warnings and exceptions we can see.  Without these settings, PDO is silent abouterror conditions.  This concept is similarly applicable to MySQL and MySQLi, where we have to control error visualization on a query-by-query basis.

 

// SET PDO TO TELL US ABOUT WARNINGS OR TO THROW EXCEPTIONS
                                        $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
                                        $pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );


CREATE TABLE Query Strings

Identical for MySQL, MySQLi, and PDO. Even though our teaching example has a very simple table structure, we will be able to see that (1) the same structure works in all extensions and (2) the same query results can be retrieved in all extensions.

 

// CREATING A TABLE FOR OUR TEST DATA
                                        $sql
                                        =
                                        "
                                        CREATE TEMPORARY TABLE my_table
                                        ( id    INT         NOT NULL AUTO_INCREMENT PRIMARY KEY
                                        , fname VARCHAR(24) NOT NULL DEFAULT ''
                                        , lname VARCHAR(24) NOT NULL DEFAULT ''
                                        )
                                        "
                                        ;


Run the CREATE TABLE Query and Handle Errors/Exceptions

MySQL and MySQLi extensions use a similar-looking construct to run the query.  MySQL calls the mysql_query() function.  MySQLi calls the query() method on the MySQLi object.  The PDO extension calls the query() method on the PDO object.  We wrap this in a try/catch block that will enable us to handle any exceptional conditions. The exception, if any, will be reported to the script in the PDOException object.


MySQL

// RUN THE QUERY TO CREATE THE TABLE
                                        $res = mysql_query($sql);
                                        
                                        // IF mysql_query() RETURNS FALSE, LOG AND SHOW THE ERROR
                                        if (!$res)
                                        {
                                            $err
                                            = "QUERY FAIL: "
                                            . $sql
                                            . ' ERRNO: '
                                            . mysql_errno()
                                            . ' ERROR: '
                                            . mysql_error()
                                            ;
                                            trigger_error($err, E_USER_ERROR);
                                        }
                                        // SHOW THE RESULTS OF THE QUERY
                                        var_dump($res);

  MySQLi


// RUN THE QUERY TO CREATE THE TABLE
                                        $res = $mysqli->query($sql);
                                        
                                        // IF mysqli::query() RETURNS FALSE, LOG AND SHOW THE ERROR
                                        if (!$res)
                                        {
                                            $err
                                            = "QUERY FAIL: "
                                            . $sql
                                            . ' ERRNO: '
                                            . $mysqli->errno
                                            . ' ERROR: '
                                            . $mysqli->error
                                            ;
                                            trigger_error($err, E_USER_ERROR);
                                        }
                                        // SHOW THE RESULTS OF THE QUERY
                                        var_dump($res);


PDO

// RUN QUERY TO CREATE THE TABLE
                                        try
                                        {
                                            $pdos = $pdo->query($sql);
                                        }
                                        catch(PDOException $exc)
                                        {
                                            var_dump($exc);
                                            trigger_error($exc->getMessage(), E_USER_ERROR);
                                        }
                                        // SHOW THE RESULTS OF THE QUERY
                                        var_dump($pdos);


PDO - Prepare a Query

This code prepares a query for use by the PDO object.  We only need to prepare the query once, then it can be reused over and over with different data.  Since the query and the data are sent to the SQL engine separately, the SQL statement is protected from SQL injection.  The results of query preparation are returned to us in the form of a PDOStatement object, stored in $pdos.  Take note of line 6.  This is where we tell PDO what our input data looks like.  The colon-prefixed names are array indexes.  Important: Do not put quotes around these colon-prefixed fields!  They are named placeholders, not variables that might be used in MySQLi queries.  You can see how this lines things up if you look back at the array keys in the test data arrays.  After the query is prepared, we can call the execute() method repeatedly, passing associative arrays with named keys.  There is a query preparation analog for MySQLi, but no such preparation method for MySQL -- with MySQL we must remember to escape the data every time, and failure to escape the data correctly could result in a failed query.  Line 11 calls the prepare() method on the PDO object and returns the PDOStatement object into $pdos.


PDO

// PREPARE THE QUERY TO LOAD THE NAMES ("PREPARE" ONLY NEEDED ONCE)
                                        $sql
                                        =
                                        "INSERT INTO my_table
                                        (  fname,  lname ) VALUES
                                        ( :fname, :lname )
                                        "
                                        ;
                                        try 
                                        { 
                                            $pdos = $pdo->prepare($sql); 
                                        } 
                                        catch(PDOException $exc) 
                                        { 
                                            var_dump($exc);
                                            trigger_error($exc->getMessage(), E_USER_ERROR);
                                        }


Use an Iterator to Escape the Data and Load the Table

The programs use identical iterators, but the method calls and sequences are different.  Unlike PDO which uses prepared query statements, the MySQL and MySQLi extensions must call the mysql_real_escape_string() function or the real_escape_string() method, then use the escaped output to create the query string.


MySQL and MySQLi make the expected function/method calls.  PDO uses the execute() method on the prepared PDOStatement object.


To test for query success and show any applicable error information, MySQL and MySQLi test for FALSE return values from the function/method calls, and execute the error handler code if necessary.  PDO catches the PDOException object that would be thrown by a failing PDOStatement object.


The last insert id (AUTO_INCREMENT KEY) is retrieved on a per-connection basis.  This means that MySQL uses the data base connection resource in its call to mysql_insert_id().  For MySQLi, the number can be found in the insert_id property of the MySQLi Object.  For PDO, the script calls the lastInsertId() method on the PDO object.


MySQL

// LOADING OUR DATA INTO THE TABLE
                                        foreach ($test_names_arrays as $person)
                                        {
                                            // ESCAPE THE DATA FOR SAFE USE IN A QUERY
                                            $safe_fn  = mysql_real_escape_string($person['fname']);
                                            $safe_ln  = mysql_real_escape_string($person['lname']);
                                        
                                            // CONSTRUCT THE QUERY USING THE ESCAPED VARIABLES
                                            $sql = "INSERT INTO my_table ( fname, lname ) VALUES ( '$safe_fn', '$safe_ln' )";
                                        
                                            // RUN THE QUERY TO INSERT THE ROW
                                            $res = mysql_query($sql);
                                        
                                            // IF mysql_query() RETURNS FALSE, LOG AND SHOW THE ERROR
                                            if (!$res)
                                            {
                                                $err
                                                = "QUERY FAIL: "
                                                . $sql
                                                . ' ERRNO: '
                                                . mysql_errno()
                                                . ' ERROR: '
                                                . mysql_error()
                                                ;
                                                trigger_error($err, E_USER_ERROR);
                                            }
                                        
                                            // GET THE AUTO_INCREMENT ID OF THE RECORD JUST INSERTED - PER THE DB CONNECTION
                                            $id  = mysql_insert_id($dbcon);
                                            echo "MySQL INSERTED A ROW CONTAINING <b>$safe_fn $safe_ln</b> WITH AUTO_INCREMENT ID = $id" . PHP_EOL;
                                        }


MySQLi


// LOADING OUR DATA INTO THE TABLE
                                        foreach ($test_names_arrays as $person)
                                        {
                                            // ESCAPE THE DATA FOR SAFE USE IN A QUERY
                                            $safe_fn  = $mysqli->real_escape_string($person['fname']);
                                            $safe_ln  = $mysqli->real_escape_string($person['lname']);
                                        
                                            // CONSTRUCT THE QUERY USING THE ESCAPED VARIABLES
                                            $sql = "INSERT INTO my_table ( fname, lname ) VALUES ( '$safe_fn', '$safe_ln' )";
                                        
                                            // RUN THE QUERY TO INSERT THE ROW
                                            $res = $mysqli->query($sql);
                                        
                                            // IF mysqli::query() RETURNS FALSE, LOG AND SHOW THE ERROR
                                            if (!$res)
                                            {
                                                $err
                                                = "QUERY FAIL: "
                                                . $sql
                                                . ' ERRNO: '
                                                . $mysqli->errno
                                                . ' ERROR: '
                                                . $mysqli->error
                                                ;
                                                trigger_error($err, E_USER_ERROR);
                                            }
                                        
                                            // GET THE AUTO_INCREMENT ID OF THE RECORD JUST INSERTED
                                            $id  = $mysqli->insert_id;
                                            echo "MySQLI INSERTED A ROW CONTAINING <b>$safe_fn $safe_ln</b> WITH AUTO_INCREMENT ID = $id" . PHP_EOL;
                                        }


PDO

// LOADING OUR DATA INTO THE TABLE
                                        foreach ($test_names_arrays as $person)
                                        {
                                            // USE THE ARRAY OF KEYWORD => VALUE TO ATTACH fname AND lname
                                            try
                                            {
                                                // RUN THE QUERY TO INSERT THE ROW
                                                $pdos->execute($person);
                                            }
                                            catch(PDOException $exc)
                                            {
                                                var_dump($exc);
                                                trigger_error($exc->getMessage(), E_USER_ERROR);
                                            }
                                        
                                            // GET THE AUTO_INCREMENT ID OF THE RECORD JUST INSERTED
                                            $id  = $pdo->lastInsertId();
                                            echo "PDO INSERTED A ROW CONTAINING <b>" . $person['fname'] . ' ' . $person['lname']. "</b> WITH AUTO_INCREMENT ID = $id" . PHP_EOL;
                                        }


Create and Execute a SELECT Query

Both MySQL and MySQLi extensions follow similar patterns to escape the external data and substitute the escaped string into the SQL statement.  After the query has been run MySQL has a resource id in $res and MySQLi has a results object.


With the PDO extension we do not need to escape the external data because the data is not put into the query string, but is sent to the SQL engine separately.  Instead we create the query string using the colon-prefixed name that we will pass to the bindParam() method.  We prepare the query on line 7 of the PDO example.  


Note that the prepare process is intended to give us a scrollable results set "cursor" which would, in theory, enable us to retrieve the rows of the results set in any order we chose.  But alas, this tool is unavailable in PHP's implementation of PDO for MySQL data bases.  In spite of being a high-value request, PHP has not implemented it.  Next, we bind the :fname column with the $fname variable using the PDO::PARAM_STR constant to tell PDO that this is a string binding and not an array binding.  Then we try to execute the query.


MySQL

// CREATE AND SEND A SELECT QUERY AND TEST THE RESULTS
                                        $fname    = "RAY";
                                        $safe_fn  = mysql_real_escape_string($fname);
                                        
                                        // CONSTRUCT THE QUERY USING THE ESCAPED VARIABLE
                                        $sql = "SELECT id, lname FROM my_table WHERE fname='$safe_fn' ORDER BY lname, fname";
                                        $res = mysql_query($sql);
                                        
                                        // IF mysql_query() RETURNS FALSE, LOG AND SHOW THE ERROR
                                        if (!$res)
                                        {
                                            $err
                                            = "QUERY FAIL: "
                                            . $sql
                                            . ' ERRNO: '
                                            . mysql_errno()
                                            . ' ERROR: '
                                            . mysql_error()
                                            ;
                                            trigger_error($err, E_USER_ERROR);
                                        }
                                        // IF SCRIPT GETS HERE WE HAVE A RESOURCE-ID IN $res


MySQLi


// CREATE AND SEND A SELECT QUERY AND TEST THE RESULTS
                                        $fname    = "RAY";
                                        $safe_fn  = $mysqli->real_escape_string($fname);
                                        
                                        // CONSTRUCT THE QUERY USING THE ESCAPED VARIABLE
                                        $sql = "SELECT id, lname FROM my_table WHERE fname='$safe_fn' ORDER BY lname, fname";
                                        $res = $mysqli->query($sql);
                                        
                                        // IF mysqli_query() RETURNS FALSE, LOG AND SHOW THE ERROR
                                        if (!$res)
                                        {
                                            $err
                                            = "QUERY FAIL: "
                                            . $sql
                                            . ' ERRNO: '
                                            . $mysqli->errno
                                            . ' ERROR: '
                                            . $mysqli->error
                                            ;
                                            trigger_error($err, E_USER_ERROR);
                                        }
                                        // IF SCRIPT GETS HERE WE HAVE A RESULT OBJECT IN $res


PDO

$fname    = "RAY";
                                        
                                        // CREATE A QUERY FOR USE WITH BINDPARAM()
                                        $sql = "SELECT id, lname FROM my_table WHERE fname = :fname ORDER BY lname, fname";
                                        
                                        // CURSOR_SCROLL ALLOWS REPOSITIONING THE CURSOR - LIKE DATA_SEEK() - BUT SADLY NOT WITH MYSQL
                                        $pdos = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
                                        
                                        // BIND THE VARIABLE AND TRY THE QUERY
                                        $pdos->bindParam(':fname', $fname, PDO::PARAM_STR);
                                        
                                        try
                                        {
                                            $pdos->execute();
                                        }
                                        catch(PDOException $exc)
                                        {
                                            var_dump($exc);
                                            trigger_error($exc->getMessage(), E_USER_ERROR);
                                        }


Find the Number of Rows in the Results Set

For MySQL, the number is found by calling the mysql_num_rows() function and passing it the $res resource from the query.  With MySQLi, the number is found in the num_rows property of the $resmysqli_result object.  With PDO, the number is usually found by calling the rowCount() method on the PDOStatement object.  But... the rowCount() method may not always give you exactly what you want to know!  Please see the man page for rowCount() and read the user-contributed notes to learn about the potential ambiguities.


MySQL

// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
                                        $num     = mysql_num_rows($res);
                                        $num_fmt = number_format($num);
                                        if (!$num)
                                        {
                                            echo "<br/>QUERY: $sql ";
                                            echo "<br/>FOUND NO DATA ";
                                            echo PHP_EOL;
                                        }
                                        else
                                        {
                                            echo "<br/>QUERY: $sql ";
                                            echo "<br/>FOUND $num_fmt ROWS OF DATA ";
                                            echo PHP_EOL;
                                        }


MySQLi

// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
                                        $num     = $res->num_rows;
                                        $num_fmt = number_format($num);
                                        if (!$num)
                                        {
                                            echo "<br/>QUERY: $sql ";
                                            echo "<br/>FOUND NO DATA ";
                                            echo PHP_EOL;
                                        }
                                        else
                                        {
                                            echo "<br/>QUERY: $sql ";
                                            echo "<br/>FOUND $num_fmt ROWS OF DATA ";
                                            echo PHP_EOL;
                                        }


PDO

// DETERMINE HOW MANY ROWS OF RESULTS WE GOT
                                        $num     = $pdos->rowCount();
                                        $num_fmt = number_format($num);
                                        if (!$num)
                                        {
                                            echo "<br/>QUERY: $sql ";
                                            echo "<br/>FOUND NO DATA ";
                                            echo PHP_EOL;
                                        }
                                        else
                                        {
                                            echo "<br/>QUERY: $sql ";
                                            echo "<br/>FOUND $num_fmt ROWS OF DATA ";
                                            echo PHP_EOL;
                                        }


Retrieve the Rows of the Results Set

Using MySQL, the rows are retrieved using the mysql_fetch_array() function .  This function was chosen to illustrate why you should not use this function.  Unless you tell it otherwise, it retrieves twice as much data as is necessary to bring back the answers!  The output from print_r() will show what is going on.


With MySQLi, the rows are retrieved using the fetch_array() method on the MySQLI_Result object.  Like mysql_fetch_array() this method retrieves twice as much data is is needed to process the results.  Better choices are shown below


In the PDO example, the rows are retrieved into an array of objects by calling the fetchAll() method on the PDOStatement object. Each of these objects has a property with the name of the column name and a value equal to the column value in the respective row.  You can also retrieve the rows into a "record set" structure, which is a two-dimensional array of arrays, where the main array contains all of the rows, and each row is represented by an associative array.  A useful function for processing record sets is array_column().


MySQL

// ITERATE OVER THE RESULTS SET AS AN ARRAY TO SHOW WHAT WE FOUND
                                        echo "USING MySQL_Fetch_<i>Array</i>(): ";
                                        echo PHP_EOL;
                                        while ($row = mysql_fetch_array($res))
                                        {
                                            // ROW BY ROW PROCESSING IS DONE HERE
                                            print_r($row);
                                            echo PHP_EOL;
                                        }


MySQLi


// ITERATE OVER THE RESULTS SET AS AN ARRAY TO SHOW WHAT WE FOUND
                                        echo "USING MySQLi_Result::Fetch_<i>Array</i>(): ";
                                        echo PHP_EOL;
                                        while ($row = $res->fetch_array())
                                        {
                                            // ROW BY ROW PROCESSING IS DONE HERE
                                            print_r($row);
                                            echo PHP_EOL;
                                        }


PDO

// ITERATE OVER THE RESULTS SET TO SHOW WHAT WE FOUND
                                        echo "USING PDOStatement::FetchAll(PDO::FETCH_OBJ): ";
                                        echo "<br/>" . PHP_EOL;
                                        while ($row = $pdos->fetchAll(PDO::FETCH_OBJ))
                                        {
                                            // ROW BY ROW PROCESSING IS DONE HERE
                                            foreach ($row as $key => $obj)
                                            {
                                                echo "$key: ";
                                                print_r($obj);
                                                echo PHP_EOL;
                                            }
                                        }


Reset the Results Set Pointer

MySQL and MySQLi can reset the results set pointer in the existing results set.  We do not need to rerun the query to get to the same data for a different view.  The PHP MySQL PDO implementation does not support this.  The first row of the results set is numbered the same way as the first element of an array.  Numbering starts with zero.


MySQL

// RESET THE RESULTS SET POINTER TO THE TOP
                                        mysql_data_seek($res,0);


MySQLi


// RESET THE RESULTS SET POINTER TO THE TOP
                                        $res->data_seek(0);


Retrieve the Rows of the Results Set (Again)

With MySQL and MySQLi, each row is retrieved in the form of an object with the column name representing a property of the object that points to the value from the row of the database.  In PDO, a second retrieval is not possible; the query must be rerun, or the original results set must be saved in PHP variables so the values can be reused.


Note that retrieving the rows in the form of  objects creates an easy-to-use syntax to incorporate the results inHEREDOCvariables!  If you retrieve the rows in the form of arrays, the quoted variables must be encapsulated in curly braces for HEREDOC, making the syntax inconvenient and much harder to get right.


MySQL

// ITERATE OVER THE RESULTS SET AS AN OBJECT TO SHOW WHAT WE FOUND
                                        echo "USING MySQL_Fetch_<i>Object</i>(): ";
                                        echo PHP_EOL;
                                        while ($row = mysql_fetch_object($res))
                                        {
                                            // ROW BY ROW PROCESSING IS DONE HERE
                                            print_r($row);
                                            echo PHP_EOL;
                                        }


MySQLi


// ITERATE OVER THE RESULTS SET AS AN OBJECT TO SHOW WHAT WE FOUND
                                        echo "USING MySQLi_Result::Fetch_<i>Object</i>(): ";
                                        echo PHP_EOL;
                                        while ($row = $res->fetch_object())
                                        {
                                            // ROW BY ROW PROCESSING IS DONE HERE
                                            print_r($row);
                                            echo PHP_EOL;
                                        }


Delete a Row From the Table

MySQL and MySQLi extensions follow similar patterns to escape the external data and substitute the escaped string into the SQL statement. The PDO extension uses the by-now-familiar :name notation with colons prepended to the array index name to prepare the query statement and bind the PHP variable.  A try/catch block encloses the call to the query handler.


MySQL

// DELETE A ROW FROM THE TABLE
                                        $lname   = "O'Reilly";
                                        $safe_ln = mysql_real_escape_string($lname);
                                        
                                        // CONSTRUCT AND RUN A QUERY TO DELETE
                                        $sql = "DELETE FROM my_table WHERE lname = '$safe_ln' LIMIT 33";
                                        $res = mysql_query($sql);
                                        
                                        // IF mysql_query() RETURNS FALSE, LOG AND SHOW THE ERROR
                                        if (!$res)
                                        {
                                            $err
                                            = "QUERY FAIL: "
                                            . $sql
                                            . ' ERRNO: '
                                            . mysql_errno()
                                            . ' ERROR: '
                                            . mysql_error()
                                            ;
                                            trigger_error($err, E_USER_ERROR);
                                        }


MySQLi


// DELETE A ROW FROM THE TABLE
                                        $lname   = "O'Reilly";
                                        $safe_ln = $mysqli->real_escape_string($lname);
                                        
                                        // CONSTRUCT AND RUN A QUERY TO DELETE
                                        $sql = "DELETE FROM my_table WHERE lname = '$safe_ln' LIMIT 33";
                                        $res = $mysqli->query($sql);
                                        
                                        // IF mysqli::query() RETURNS FALSE, LOG AND SHOW THE ERROR
                                        if (!$res)
                                        {
                                            $err
                                            = "QUERY FAIL: "
                                            . $sql
                                            . ' ERRNO: '
                                            . $mysqli->errno
                                            . ' ERROR: '
                                            . $mysqli->error
                                            ;
                                            trigger_error($err, E_USER_ERROR);
                                        }


PDO

// DELETE A ROW FROM THE TABLE
                                        $lname   = "O'Reilly";
                                        
                                        // CONSTRUCT AND RUN A QUERY TO DELETE
                                        $sql = "DELETE FROM my_table WHERE lname = :lname LIMIT 33";
                                        
                                        // BIND THE VARIABLE AND TRY THE QUERY
                                        $pdos = $pdo->prepare($sql);
                                        $pdos->bindParam(':lname', $lname, PDO::PARAM_STR);
                                        try
                                        {
                                            $pdos->execute();
                                        }
                                        catch(PDOException $exc)
                                        {
                                            var_dump($exc);
                                            trigger_error($exc->getMessage(), E_USER_ERROR);
                                        }


Determine the Number of Affected Rows

MySQL calls the mysql_affected_rows() function referencing the data base connection. MySQLi reads the affected_rows property from the MySQLi object. PDO calls the rowCount() method on the PDOStatement object.


MySQL

// HOW MANY ROWS WERE AFFECTED BY DELETE?
                                        $num     = mysql_affected_rows($dbcon);
                                        $num_fmt = number_format($num);
                                        if (!$num)
                                        {
                                            echo "<br/>QUERY: $sql ";
                                            echo "<br/>AFFECTED NO DATA ";
                                            echo PHP_EOL;
                                        }
                                        else
                                        {
                                            echo "<br/>QUERY: $sql ";
                                            echo "<br/>AFFECTED $num_fmt ROWS OF DATA ";
                                            echo PHP_EOL;
                                        }


MySQLi


// HOW MANY ROWS WERE AFFECTED BY DELETE?
                                        $num     = $mysqli->affected_rows;
                                        $num_fmt = number_format($num);
                                        if (!$num)
                                        {
                                            echo "<br/>QUERY: $sql ";
                                            echo "<br/>AFFECTED NO DATA ";
                                            echo PHP_EOL;
                                        }
                                        else
                                        {
                                            echo "<br/>QUERY: $sql ";
                                            echo "<br/>AFFECTED $num_fmt ROWS OF DATA ";
                                            echo PHP_EOL;
                                        }

PDO

 

// HOW MANY ROWS WERE AFFECTED BY DELETE?
                                        $num     = $pdos->rowCount();
                                        $num_fmt = number_format($num);
                                        if (!$num)
                                        {
                                            echo "<br/>QUERY: $sql ";
                                            echo "<br/>AFFECTED NO DATA ";
                                            echo PHP_EOL;
                                        }
                                        else
                                        {
                                            echo "<br/>QUERY: $sql ";
                                            echo "<br/>AFFECTED $num_fmt ROWS OF DATA ";
                                            echo PHP_EOL;
                                        }


Visualize Error and Exception Information

A defective query is created to cause a failure of the MySQL server.  Each of the MySQL extensions creates its own error information, which is displayed by the script.  The PDOException object is far more comprehensive in its information.  It would require considerable programming to get this kind of detailed information from MySQL or MySQLi. In the case of PDO, note that the PDOStatement object is not modified by the query failure and still contains the previous query statement.


MySQL

// CONSTRUCT A QUERY THAT WILL FAIL
                                        $sql = "SELECT oopsie FROM my_table ";
                                        $res = mysql_query($sql);
                                        
                                        // SHOW THE ERROR INFORMATION
                                        if (!$res)
                                        {
                                            $err
                                            = "QUERY FAIL: "
                                            . $sql
                                            . ' ERRNO: '
                                            . mysql_errno()
                                            . ' ERROR: '
                                            . mysql_error()
                                            ;
                                            echo $err;
                                        }


QUERY FAIL: SELECT oopsie FROM my_table  ERRNO: 1054 ERROR: Unknown column 'oopsie' in 'field list'


MySQLi


// CONSTRUCT A QUERY THAT WILL FAIL
                                        $sql = "SELECT oopsie FROM my_table ";
                                        $res = $mysqli->query($sql);
                                        
                                        // SHOW THE ERROR INFORMATION
                                        if (!$res)
                                        {
                                            $err
                                            = "QUERY FAIL: "
                                            . $sql
                                            . ' ERRNO: '
                                            . $mysqli->errno
                                            . ' ERROR: '
                                            . $mysqli->error
                                            ;
                                            echo $err;
                                        }


QUERY FAIL: SELECT oopsie FROM my_table  ERRNO: 1054 ERROR: Unknown column 'oopsie' in 'field list'


PDO

// CONSTRUCT A QUERY THAT WILL FAIL
                                        $sql = "SELECT oopsie FROM my_table ";
                                        try
                                        {
                                            $pdos = $pdo->query($sql);
                                        }
                                        catch(PDOException $exc)
                                        {
                                            // SHOW PDOException AND PDOStatement
                                            var_dump($exc);
                                            var_dump($pdos);
                                        }


object(PDOException)#5 (8) {
                                          ["message":protected]=>
                                          string(79) "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'oopsie' in 'field list'"
                                          ["string":"Exception":private]=>
                                          string(0) ""
                                          ["code":protected]=>
                                          string(5) "42S22"
                                          ["file":protected]=>
                                          string(49) "/home/account/public_html/RAY_EE_pdo_example.php"
                                          ["line":protected]=>
                                          int(284)
                                          ["trace":"Exception":private]=>
                                          array(1) {
                                            [0]=>
                                            array(6) {
                                              ["file"]=>
                                              string(49) "/home/account/public_html/RAY_EE_pdo_example.php"
                                              ["line"]=>
                                              int(284)
                                              ["function"]=>
                                              string(5) "query"
                                              ["class"]=>
                                              string(3) "PDO"
                                              ["type"]=>
                                              string(2) "->"
                                              ["args"]=>
                                              array(1) {
                                                [0]=>
                                                string(28) "SELECT oopsie FROM my_table "
                                              }
                                            }
                                          }
                                          ["previous":"Exception":private]=>
                                          NULL
                                          ["errorInfo"]=>
                                          array(3) {
                                            [0]=>
                                            string(5) "42S22"
                                            [1]=>
                                            int(1054)
                                            [2]=>
                                            string(39) "Unknown column 'oopsie' in 'field list'"
                                          }
                                        }
                                        object(PDOStatement)#3 (1) {
                                          ["queryString"]=>
                                          string(50) "DELETE FROM my_table WHERE lname = :lname LIMIT 33"
                                        }


Conclusion

With more than 8 years of experience using the PDO Extension API, we can be confident that the API is debugged and ready for "prime time."  The same can be said for the MySQLi Extension.  And given the current status of MySQL, it's time to upgrade our scripts.  This article has shown some links to the relevant man pages and some examples that illustrate the programming changes required to keep our programming running in the modern age.


The MySQL Obsolete Complete Code Example


32
 
LVL 111

Author Comment

by:Ray Paseur
Comment Utility
@COBOLdinosaur:  I am seeing the same.  I have also verified that you can open simultaneous MySQL and MySQLi connections to the data base server and run some queries one way and other queries another.  I have not tested this with PDO yet, but I expect that PDO will also facilitate multiple connections.  All of this will make the transitions easier.
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
Comment Utility
I am in the process of migrating now, and I can confirm that using bth types of connects works fine.  There is a slight cost in DB overhead (less than .1%), and I am not see any response time penalty using them together.  

It means rather than having to take an outage and rush through a mass move, I can mix and match and do a slow careful migrate of single modules and avoid ooops! moments.  Once I have everything migrated, I will be able to cutover to PHP 5.5 knowing that everything ran in PHP in a test environment; so all it will take is changing the parser to 5.5 because all the code is know to run at that level.

Best of all ZERO DOWN TIME for a complete migration to PHP 5.5 including converting to PDO.

Cd&
1
jQuery is a JavaScript library that greatly simplifies JavaScript programming.

AJAX is an acronym formed from "Asynchronous JavaScript and XML."  AJAX refers to any communication between client and server, when the human client does not observe a new page load.  An HTTP request occurs, but it occurs as a result of a JavaScript event, rather than an explicit page load or form submission.  As a result, the web page takes on an appearance much like a desktop application, with smooth transitions as data is added or removed from the viewport.  This is often referred to as the "Web 2.0" effect.

I found myself looking around for a jQuery/AJAX "Hello World" example (that simplest of scripts to prove that the essential moving parts are working correctly).  There are lots of partial examples in many different places all over the WWW, but nothing seemed complete and well-documented, so I decided to write my own.  Here is the result of that effort.

The Server-Side of the Exercise
To make my example, I decided the essential parts would be the ability to send some data to the server and get a response back, so the first part of the exercise is the server-side script that produces a response containing the data it received from the AJAX request.  AJAX provides a RESTful interface.  The data for the request is sent via GET or POST and the response from the server is sent in the form of browser output.  As a result, it is very easy to test the back-end script. …
19
 

Expert Comment

by:Nico2011
Comment Utility
Thanks Ray - very helpful - hope you are well!
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
Comment Utility
It is very helpful.
0
HTML 5 is the latest buzz in developing RIA (Rich Internet Application). One the best features in HTML 5 is Web Storage!

It's really amazing and powerful. It totally replaces the traditional Cookies!

HTML 5 Web Storage is of two types -

1. Local Storage
2. Session Storage

I discussed Local Storage on my blog (see below) but will discuss Session Storage in detail here, so that you can kick start using it at once, when you are done reading this article.

Local Storage

I already discussed about Local Storage on my blog - Local Storage - Avoid Cookies

Session Storage

In contrast to Local Storage, the lifetime of this storage is per session. When the user closes the browser, the stored data expires.  It just stores data for particular session.

Similar to Session in Server Side Programming( ASP.NET, PHP ), it just holds the data in  Client Side.

Unlike Cookies, it won't travel with each request to the server. It will be available in the browser and it can be retrieved when it requires.

Storing and retrieving data in the Session Storage is  pretty simple!

Store data in Session Storage!

<script type="text/javascript">
//Check whether the browser supports Session Storage, if yes, then store the data.
if (window.sessionStorage) {
            sessionStorage.myName = "Session Storage";
        }
</script>

Open in new window


Data is stored as Key/Value pair! So in the above code -

myName  is Key, Session Storage is Value
2
 
LVL 23

Author Comment

by:Roopesh Reddy
Comment Utility
Hi,

I'm done updating the information suggested by the users!
0
 

Expert Comment

by:Dinesh Kumar
Comment Utility
can you help in telling where localstorage gets stored in computer?
0
Introduction
This article briefs you about siteminder and its various tools available for integration with your web applications. This is just an overview to know about siteminder tools. There are lot of documentation available in the CA Netigrity website (Reference section below).  

Purpose
The web user can securely access the web application using Siteminder API. Only a validated user can navigate through the web application.  Integration of authentication and authorization with the web application can be easily achieved using Siteminder tools.

How it works?
The siteminder consists of set of tools which help in securing the website and also used for Authentication & authorization of the web application.

The main 2 components of the siteminder are
1.      Webagent
2.      Policy Server.

The webagent acts as a proxy between your browser and the web server, any request that comes to the webserver is filtered, validated before the request is forwarded to the webserver. The authentication and authorization is performed using Siteminder Policy server.

Siteminder Webagent
Siteminder webagent is used to filter all the http request that comes from the web browser to the webserver. The webagent secures the webserver to make sure only validated user is allowed to the view the web application.

Policy Server
The siteminder webagent uses the site minder policy server for Authentication & Authorization. The siteminder policy server in …
4
      Install BugTracker on Windows 2008 server


Step 1:  Install windows 2008 server 32 bit OS and configure IIS.

Step 2:  Install SQL server ( SQL server 2005 or SQL server 2005 Express edition. The installer for 2008  version isn’t very friendly) on the machine

Step 3: Install .net framework 4.0.

Step 4:       Download bugtacker.net from the link http://ifdefined.com/bugtrackernet_download.html

Step 5:  Extract the zip file into a folder. Here we used a folder name “bugtracker” and place the folder  into C:\inetpub\wwwroot\

Step 6:  Create the IIS virtual directory or application

Step 7: Open IIS 7, create an Application and map it to the "www" subfolder.

1
2
Step 8: Step 8: Open SQL server management studio and create a database. Name it whatever you want. Here we have using “bugtracker” as the database name.

3
4
Step 9: Modify the "ConnectionString" setting in Web.config to point to your database server and newly created database.

     1.      Open web.config file from C:\inetpub\wwwroot\bugtracker\www\
     2.      Find the connection string

Default connection string

5
After changing the value of connection String

6
Step 10: Now try to open the website. If you got an error like the below image please do the following steps in IIS.

7
           1.       Open Application Pool in the IIS
               8
           2.       Change the .NET framework version to v4.0
                9
0
 

Expert Comment

by:vichuu
Comment Utility
excellent one..its working...thank you very much.
0

Things That Drive Us Nuts

Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this. An evil CAPTCHA imageInsanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is a far cry from a good user experience.


This article is about how to apply some sanity in the CAPTCHA process.  It does not have to cause eyestrain for your clients, and it will likely be nearly as secure as the agonizing and unreadable stuff that reCaptcha cranks out.  In the process of creating an image-based CAPTCHA test, we will learn something about PHP image manipulation.


Anti-Spam and Anti-'Bot Tools (Power to the People)

The term CAPTCHA is "sort of" an acronym.  It stands for Completely Automated Public Test (to tell) Computers and Humans Apart.  The theory is fairly simple.  Your server-side script gives the client a test that a human can pass easily but a computer cannot readily understand.  You can read more about the theory and implementations here, and in the Wikipedia.

http://en.wikipedia.org/wiki/CAPTCHA


Invisible CAPTCHA

A "honeypot" is a form element that should not be filled in when a human completes the form.  You can give a form input control a tempting name, like "email" and style the input with CSS to make it invisible on the browser.  If the form contains any data in the tempting input field, you can discard the request, since this would not have come from a human being.


 

<?php // RAY_honeypot.php
                                        error_reporting(E_ALL);
                                        
                                        // DEMONSTRATE A HONEYPOT CAPTCHA TEST
                                        
                                        // IF THE FORM HAS BEEN FILLED IN
                                        if (!empty($_POST))
                                        {
                                            // IF THE HONEYPOT HAS BEEN FILLED IN
                                            if (!empty($_POST['email'])) trigger_error("BE GONE, ATTACK BOT!", E_USER_ERROR);
                                        
                                            // PROCESS THE REST OF THE FORM DATA HERE
                                            var_dump($_POST);
                                        }
                                        
                                        // CREATE THE FORM
                                        $form = <<<EOD
                                        <style type="text/css">
                                        .honey {
                                            display:none;
                                        }
                                        </style>
                                        <form method="post">
                                        <input name="email" class="honey" />
                                        <input name="thing" />
                                        <input type="submit" />
                                        </form>
                                        EOD;
                                        
                                        echo $form;


Minimalist CAPTCHA

One step up from an invisible CAPTCHA might be a checkbox that says, "Check this box to prove you're a human."  Not very deep, but arguably effective in a limited way.  And there is this from the endearing "A Word a Day" site. A simple and effective CAPTCHA from WordSmith.orgAnother simple design pattern is a form field that has a value filled in.  The web page asks the human to clear the field before submitting the form. A simple and effective CAPTCHA testVisually Based CAPTCHA Test

To reduce the risk of automated registration, the Craftsy web site uses a simple visual CAPTCHA.  The client is asked what animal is shown.  Craftsy may find the 1:4 ratio of possibilities acceptable; statistically speaking, an attack 'bot could be right about the animal 25% of the time.  If Craftsy couples its CAPTCHA with some kind of email verification this is probably acceptable protection. Animal-based CAPTCHA imageAt a slightly higher level, when there is common knowledge in a community, you might ask the client to enter the name of, for example, the school mascot.  The server-side verification for these tests is very simple, usually only a single if() statement.


A CAPTCHA Test with Simple Arithmetic

You can copy this script, put it on your server and run it to see the effect.  The script chooses two numbers at random, then chooses among several possible arithmetic operations to produce a CAPTCHA test that writes out an English-language simple math problem.  The client experience in this structure is very similar to the CAPTCHA test on the comment feature of the PHP.net web site.  It is easy to implement and easy for the client to use, but for a 'bot to readily defeat it, there would be a lot of programming required.  The web site would use the getQuestion() method in the HTML form script, and would use the testAnswer() method in the action= script. Give it a try, and if it's good enough for your work, enjoy it.  And if you feel you need greater obscurity, read on below for the image-based CAPTCHA tests.

 

15
 
LVL 111

Author Comment

by:Ray Paseur
Comment Utility
Found an interesting twist on the CAPTCHA problem:
http://areyouahuman.com/

Of course it suffers from the same risks of outsourcing noted above, "I could outsource to a low-wage country to have a group of people refresh your page for 2 days to gather a list of all the images you use."  The technique to defeat this animated test is slightly different from gathering a list of images, but the point of using people to defeat CAPTCHA begs the question, "If we want to avoid 'bots and allow humans, and we get humans, are we happy with the process and outcome?"
0
 
LVL 75

Expert Comment

by:Michel Plungjan
Comment Utility
The new RECaptcha is available

https://www.google.com/recaptcha/intro/index.html
0
Foreword (July, 2015)
Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing rate.  I expected that nascent trend would continue, and it has.  Everyone seems to recognize the trend.  Yet to my amazement, relatively few web sites serve their content in any language other than English.  Of course, why bother?  Isn't English the language of technology?

Well, yes, English is the language of technology, but this is not about technology; it's about human nature.  If you're in business to make money, a monoglot web site is a handicap and huge blind spot.  If you're wondering whether it's economically feasible to offer site translations, this Tech.Co article may help you make up your mind.  In its summary quote, we find this: "The good news is that the potential return on your investment is significant.  Studies suggest that for every $1 spent on localization you can expect to see a $25 return."

There aren't many places you can get ROI like that!  To learn how it's done, read on...

Introduction
This article describes the general design elements of a multilingual web site. The site will be very simple, but all the important parts of the design will be present. Here are two images that show what the site looks like.  By clicking on the flags at the bottom, our clients can change the languages. Two examples showing English and German
6
 
LVL 70

Expert Comment

by:Jason C. Levine
Comment Utility
Very nice.
0
 
LVL 15

Expert Comment

by:Eric AKA Netminder
Comment Utility
Ray_Paseur,

Congratulations; your article has been selected as EE-Approved.

ericpete
Page Editor
0
Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit and similar technologies have enjoyed wide adoption, making it possible to write and share unit tests among teams of programmers.  Behat and similar technologies (Laravel, for example) have introduced fluency into the programming process.  Taken together, these advances have brought open-source programming into a state that is somewhat similar to musket making, just after Eli Whitney.  If you're here looking for guidance about modernizing your development process, please take some time to learn about these "new technologies" because you will soon be unemployable if you're not conversant in the details.  These are the greatest advances in software development in our generation.

Now back to our Test-Driven Development article...

On Monday, October 17, 2011, the A.Word.A.Day "Thought for Today" was "A problem well stated is a problem half solved." -- attributed to Charles F. Kettering, inventor and engineer (1876-1958).

The Greatest Handicap a Programmer Can Have
The author of a question here at EE wrote. "I have no test data besides some stuff I can come up with."
http://www.experts-exchange.com/Programming/Languages/Regular_Expressions/Q_27305841.html#a36556359
15
 
LVL 84

Expert Comment

by:Dave Baldwin
Comment Utility
That exactly corresponds to the date problem.  For whatever reason, the end-user is allowed to enter an unacceptable format.  If it was on my web page, I'd make it a drop-down or radio boxes that only allow the proper formats.  Like I said above, let the salesman test it, they always get it wrong.
0
 
LVL 49

Expert Comment

by:PortletPaul
Comment Utility
Ray, you write so well and with passion, another impressive article. I have an admission to make however, my "eyes glaze over" when I see regex patterns :)

I'm also led to wonder why on earth we allowed things like .com without a geo reference first up, and that the sequence wasn't "top down". That is why is the Top level domain last? :) Heaven knows what will happen with TLD's in the future too (e.g. generic names)  - be prepared for regular revisits.

Such is life.

Programming without test data is the practice of clairvoyancy.
1
Quite often, your web application, web site, AJAX code or web service does not work in the way you expect it to.
In these cases, it may be necessary to "look under the hood" of the http protocol and to look at either client requests, server replies or both.
You also need the ability to resend some requests over and over again, especially when dealing with AJAX and web services.

The explanations assume some knowledge of XML, HTML, and HTTP, as well as scripting skills.
 

1. Web Services


Debugging web services can be a major pain in the backside. Lucky for us, there is a set of tools and techniques that can help us simulate and trace web services and AJAX requests.
These tools are described as test tools, but I've successfully used them in production environments as a way to invoke web services and web server side actions from custom scripts.

Conventions used in all of the tool usage descriptions:
*  = the web service action to initiate
*  = a [][XML]] file with the entire SOAP envelope and payload
*  = where you want to save the results
*  = the web service address URL

====Testing using curl====
curl is a command line tool that supports all URL protocols. It is availble for multiple platforms and can be found here: http://curl.haxx.se/ .
It can be easily used for regular web sites, and works well with SOAP and WS.

 
curl --request POST --header "SOAPAction: <action>" --header "Content-type: text/xml" --data @<xmlfile> -o <outputfile> <SOAPUrl>

Open in new window


====Testing using SOAPClient4XG (SOAP client For XML Geeks)====
See IBM DeveloperWorks web site at
3

Web Applications

14K

Solutions

14K

Contributors

Web applications are systems that run in browsers that perform functions normally associated with other client-based programs. One of the most commonly used web applications is email; instead of downloading individual emails to a local machine, the data is shown through a website. Other examples of web applications are collaborative systems like a wiki or an online game.