Category: Zend Framework

For this example, let’s say you have a site you want to post data to so a newly trained employee is added to a mailing list.  In the older days of php, you could do this with http_post_params; however, this function is now deprecated.  Instead, you can use the curl method, or you can use some Zend libraries.

Since this is a post on using Zend, I think you know which one I chose to do.

The following example is a really simple one.  I’m just using a configuration file to hold my options and parameters to use for creating a curl request.  Then I have a script that reads the config  file, creates the request, sends the request, and then checks the response.

The Configuration File

; --configuration file /configFile/myConfig.ini

;connection info
 curl.mailingList.adapter = Zend_Http_Client_Adapter_Curl
 curl.mailingList.uri = ""

;authentication/post parameters
 curl.mailingList.postParameter.APIUSER = "admin_user"
 curl.mailingList.postParameter.APIPWD = 'some_password'

;configuration options
 curl.mailingList.options.curloptions[CURLOPT_RETURNTRANSFER] = true
 curl.mailingList.options.curloptions[CURLOPT_HEADER] = false
 curl.mailingList.options.curloptions[CURLOPT_ENCODING] = ""
 curl.mailingList.options.curloptions[CURLOPT_AUTOREFERER] = true
 curl.mailingList.options.curloptions[CURLOPT_CONNECTTIMEOUT] = 120
 curl.mailingList.options.curloptions[CURLOPT_TIMEOUT] = 120
 curl.mailingList.options.curloptions[CURLOPT_MAXREDIRS] = 10
 curl.mailingList.options.curloptions[CURLOPT_POST] = 1
 curl.mailingList.options.curloptions[CURLOPT_VERBOSE] = 1
 curl.mailingList.options.timeout = 120
 curl.mailingList.options.maxredirects = 10

Performing the Curl

To actually perform the curl, we will need to load the configuration file into our code and then prepare the curl to send.

 * Create a post request to add a new trainee to the mailing list
 * PHP Version 5
 * @created 10/12/2011
 * @updated 10/12/2011

 * Include the Zend_Loader class
require_once 'Zend/Loader.php';

//load the needed Zend libraries
Zend_Loader::loadClass('Zend_Config_Ini');  //for reading the configuration file

//read in the configuration file
$config = new Zend_Config_Ini('/configFile/myConfig.ini', 'production');

//setup our post params (subscribees is the name of the form field)
$postParam = array('subscribees' => '');

//try to create and send the curl
        //setup the curl connection
        $adapter = new Zend_Http_Client_Adapter_Curl();

        //instantiate the http client and add set the adapter
        $client = new Zend_Http_Client($config->curl->mailingList->uri);

        //add the post parameters from our config file (the authentication part)

        //add our post parameters to the request

        //perform the post, and get the response
        $response = $client->request(Zend_Http_Client::POST);

        //check the response for success
        if (strpos($response, "<h5>Successfully subscribed:</h5>") !== false) {

            echo "<p>Added {$fullName} to trainee email list successfully.</p>";

        } else if (strpos($response, "Already a member") !== false) {

            echo "<p>Already a member of the trainee email list";

        } else {

             echo "<p style='color: red;'>ERROR: Not added to the trainee email list</p>";
catch (Zend_Http_Client_Adapter_Curl_Exception $e)
    echo "<p style='color: red;'> ERROR: Failed to add the employee to the trainee email list.</p>";
catch (Zend_Http_Client_Exception $e)
     echo "<p style='color: red;'> ERROR: Failed to add the employee to the trainee email list.</p>";

As you can see, the script is not very complex. But it could be expanded to handle logging of errors and other functionality.

Zend Framework offers a very robust solution for almost any kind of web site; however, there are times when all you want to do is connect to a database without the need for the rest of the framework.  Bellow I will show a quick example of how to connect to two different databases using the Zend_Db, Zend_Config_Ini, and Zend_Loader  classes.

First you need to define your ini file (make sure to store this file out side of the web root, mine is stored at /var/)

; PostgreSQL database connection info
db.pgsqlServer.adapter = PDO_PGSQL = server_ip_or_url
db.pgsqlServer.config.dbname = database_name
db.pgsqlServer.config.username = "dbuser"
db.pgsqlServer.config.password = "dbpassword"

; Microsoft SQL Server database connection info
db.mssqlServer.adapter = PDO_MSSQL
db.mssqlServer.config.pdoType = dblib = server_ip_or_url
db.mssqlServer.config.dbname = database_name
db.mssqlServer.config.username = "mssql_user"
db.mssqlServer.config.password = "mssql_password"

From the above ini file contents, there are a few things to take note of:

  1. You need to define the pdoType as dblib when connecting to MSSQL with the  PDO Adapter (the default type mssql is not available in the php5_sybase package)
  2. You can set driver_options (attributes) for the PDO connection, some of the attributes you can set are
    1. PDO::ATTR_ERRMODE = PDO::ERRMODE_EXCEPTION             (throw exceptions)
    2. PDO::ATTR_PERSISTANT = true                                                  (make persistent connections)
    3. PDO::ATTR_DEFAULT_FETCH_MODE=PDO::FETCH_ASSOC   (return an associative array when fetching query result by default)

Next, create your php file that will be using the database connections. For this example, my php file is located at /var/www/example_project and the Zend libraries are located at include/libs/Zend

//set the include path for Zend Framework (the include path is not defined in php.ini)
set_include_path('include/libs' . PATH_SEPARATOR . get_include_path());

//Include the Zend_Loader class
require_once 'Zend/Loader.php';

//load the Zend classes for use

//load the configuration file
$config = new Zend_Config_Ini('/var/my_example.ini', 'production');

//try to connect to and work with the postgres database
     //connect to postgresql
     $dbh = Zend_Db::factory(

     //set the instructor id number to use for the query
     $instructorID = 1234;

     //define the query
     $sql = "SELECT Full_Name From Trained WHERE train_id = :idNumber";

     //prepare the query
     $stmt = $dbh->prepare($sql);

     //bind the instructor id as an integer data type to the query
     $stmt->bindParam(':idNumber', $instructorID, PDO::PARAM_INT);

     //execute the query

     //if an instructor with the given id exits
     if ($stmt->rowCount() > 0) {

         $row = $stmt->fetch(PDO::FETCH_ASSOC);
         echo "The instructors full name is: ",$row['full_name'];

     //clear the statement
     $stmt = null;

     //close the database connection

catch (PDOException $e)
     //echo $e->getMessage();
     echo "There was an error querying the database";
catch (Zend_Db_Adapter_Exception $e)
     //echo $e->getMessage();
     echo "Unable to connect to the database";
catch (Exception $e)
     echo $e->getMessage();

In the above example, I only connected to and used the Postgres database since the code for using either database is almost exactly the same.  The only thing you would need to change in the above code to use the MSSQL database would be to change the pgsqlServer part in the Zend_Db::factory() parameters to mssqlServer.

In closeing the catch blocks at the bottom the php file do the following

  • PDOException – Catches any exception thrown by PDO while working with the database (in this example, this pertains to querying the database)
  • Zend_Db_Adapter_Exception – Catches any exception thrown while trying to connect to the database (or while using Zend_Db_Adapter, the $dbh variable)
  • Exception – Catches any other exceptions I missed