_php examples of zend_db_table usage in Zend framework tutorials

Source: Internet
Author: User
Tags abstract first row zend zend framework

The examples in this article describe zend_db_table usage. Share to everyone for your reference, specific as follows:

1. Introduction

Zend_db_table is a table module for the Zend framework. It connects to the database through Zend_db_adapter, checks the table object for the database schema, and operates and queries the table.

2. Start

First you need to zend_db_table the abstract class (Ares Note: The class is abstract, so you cannot instantiate it directly, you can only inherit the class and then instantiate the subclass) to set a default pair of database adapter; Unless you specify another type of database adapter, all Zend_ Db_table class instances use the default adapter.

<?php
//Establish a adapter
require_once ' zend/db.php ';
$params = Array (
  ' host '   => ' 127.0.0.1 ', '
  username ' => ' malory ',
  ' password ' => '),
  ' dbname '  => ' Camelot '
);
$db = zend_db::factory (' Pdo_mysql ', $params);
Set the default adapter
require_once ' zend/db/table.php ' for all zend_db_table objects;
Zend_db_table::setdefaultadapter ($db);
? >

Next, we assume that there is a table named "Round_table" in the database. To use zend_db_table for this table, simply inherit the Zend_db_table class and create a The new class. Then I can check the round_table table in the database by this class, manipulate the data rows and get the data results.

<?php
Class Roundtable extends Zend_db_table {}
$table = new Roundtable ();
? >

3. Table name and PRIMARY key

By default, the Zend_db_table class takes its class name as a table name in the database (you need to add "_" where the capitalization is different). For example, a zend_db_table class named Sometablename is in the database for the corresponding table "Some_table_ Name ". If you do not want the class name to correspond with the database table name in this underlined form, you can refactor the $_name when you define the class.

<?php
class ClassName extends zend_db_table
{/
  /default table name is ' class_name '
  //But we can also correspond to other tables
  protected $_name = ' another_table_name ';
}
? >

The Zend_db_table class default field "ID" is the primary key for the table (the field is preferably self added, but not required). If the primary key of the table is not named "$id", you can refactor the $_primary when defining the table entity class

<?php
class ClassName extends zend_db_table
{//
  default primary key is ' ID '
  //But we can also set other column names as the primary key
  protected $_primary = ' another_column_name ';
>

You can also set these variables by using the _setup () method in the table entity class, but you need to make sure that the Parent::_setup () method is executed again after the modification.

<?php
class ClassName extends zend_db_table
{
  protected function _setup ()
  {
    $this->_name = ' Another_table_name ';
    $this->_primary = ' another_column_name ';
    Parent::_setup ();
  }
? >

4. Inserting data

To insert a row of new data into a table, simply invoke the Insert () method by calling the column name: an associative array of data as a parameter.

(Zend Framework) automatically quotes the data and returns the ID value of the last line inserted
(Note: This is different from the Zend_db_adapter::insert method, which returns the number of rows inserted).

<?php////
INSERT into round_table
//   (Noble_title, first_name, Favorite_Color)
//   VALUES ("King", "Arthur", "Blue")
//
Class Roundtable extends Zend_db_table {}
$table = new Roundtable ();
$data = Array (
  ' noble_title ' => ' King ', '
  first_name ' => ' Arthur ',
  ' favorite_color ' => ' Blue ', c27/>)
$id = $table->insert ($data);
? >

5. Update data

To modify any row of data in a table, we can set a column name: An associative array of data as a parameter, call the update () method, and use a WHERE conditional clause to determine which row to change. The method modifies the data in the table and returns the number of rows that were modified.

(Zend Frameword) will automatically enclose the data in quotation marks, but this check does not include the conditional clause, so you need to use the Zend_db_adapter object of the table to do the work.

Class Roundtable extends Zend_db_table {}
$table = new Roundtable ();
$db = $table->getadapter ();
$set = Array (
  ' favorite_color ' => ' yellow ',
)
$where = $db->quoteinto (' first_name =? ', ' Robin ');
$rows _affected = $table->update ($set, $where);

6. Deleting Rows

To delete the data in the table, we can call the Delete () method and determine the rows that need to be deleted by using a WHERE condition clause. The method will return the number of rows that were deleted.

(Zend Framework) does not enclose conditional clauses in quotes, so you need to use the table's Zend_db_adapter object to do the job

<?php
///
DELETE from round_table//   WHERE first_name = "Patsy"
//
Class Roundtable Extends Zend_db_table {}
$table = new Roundtable ();
$db = $table->getadapter ();
$where = $db->quoteinto (' first_name =? ', ' Patsy ');
$rows _affected = $table->delete ($where);
? >

7. Find data based on primary key

By invoking the Find () method, you can easily retrieve data from a table by using primary key values. If you only want to query a particular piece of data, the method returns a Zend_db_table_row object, and when you want to query multiple records, you return a zend_db_table_ Rowset object.

<?php
Class Roundtable extends Zend_db_table {}
$table = new Roundtable ();
SELECT * FROM round_table WHERE id = "1"
$row = $table->find (1);
SELECT * FROM round_table WHERE ID in ("1", "2", 3 ")
$rowset = $table->find (Array (1, 2, 3));
? >

8. Retrieve a record

Although it is convenient to find the corresponding data rows through the primary key, in more times, we are looking for data rows through other non primary key conditions. Zend_db_table provides a fetchrow () method to implement this functionality. We can use a WHERE condition statement ( and an optional order statement) calls the Fetchrow () method, and then Zend_db_tabel returns the Zend_db_table_row object that satisfies the first row of the condition.

Note that the (Zend Framework) will not quote the WHERE statement, so you need to process the data by Zend_db_adapter

<?php
///
SELECT * from round_table
//   WHERE noble_title = "Sir"
//and   first_name = "Robin "
//ORDER by   Favorite_Color
//
Class Roundtable extends Zend_db_table {}
$table = new Roundtable ();
$db = $table->getadapter ();
$where = $db->quoteinto (' Noble_title =? ', ' Sir ')
    . $db->quoteinto (' and first_name =? ', ' Robin ');
$order = ' Favorite_Color ';
$row = $table->fetchrow ($where, $order);
>

9. Retrieve more than one record

If you need to retrieve more than one record at a time. You can use the Fetchall () method. Similar to using the Fetchrow () method, this method can not only set the WHERE and order clauses, but also set the Limit-count and Limit-offset value to limit the number of results returned. After the method is executed, the result of the selection is returned as a Zend_db_table_rowset object.
Note that the (Zend Framework) will not quote the WHERE statement, so you need to process the data by Zend_db_adapter.

<?php
Class Roundtable extends Zend_db_table {}
$table = new Roundtable ();
$db = $table->getadapter ();
SELECT * FROM round_table
//   WHERE noble_title = ' Sir '
//ORDER by   first_name
//   LIMIT SET
$where = $db->quoteinto (' Noble_title =? ', ' Sir ');
$order = ' first_name ';
$count = ten;
$offset =;
$rowset = $table->fetchall ($where, $order, $count, $offset);
>

Adding Domain Logic

As a table module of the Zend framework, zend_db_table encapsulates itself well under the unique domain logic. For example, you can overload the Insert () and update () methods to implement operations and validation before data changes are committed.

<?php
Class Roundtable extends zend_db_table
{public
  function Insert ($data)
  {
    //Add a timestamp
    if (Empty ($data [' created_on ']) {
      $data [' created_on '] = time ();
    }
    Return Parent::insert ($data);
  Public Function Update ($data)
  {
    //Add a timestamp
    if (Empty ($data [' updated_on '])) {
      $data [' updated_on '] ] = time ();
    }
    Return Parent::update ($data);
  }
? >

Similarly, you can set your own find () method to query for data from other fields outside the primary key.

<?php
Class Roundtable extends zend_db_table
{public
  function findallwithname ($name)
  {
    $db = $this->getadapter ();
    $where = $db->quoteinto ("name =?", $name);
    $order = "First_Name";
    return $this->fetchall ($where, $order);
  }
? >

More interested in Zend related content readers can view the site topics: "The introduction of the Zend Framework frame", "PHP Excellent Development Framework Summary", "Yii framework Introduction and common skills Summary", "thinkphp Introductory Course", "PHP object-oriented Programming Program , "Php+mysql Database operation Introduction Tutorial" and "PHP common database Operation Skills Summary"

I hope this article will help you with the PHP program design based on the Zend Framework.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.