Team LiB
Previous Section Next Section

PEAR DB Module Methods

The following descriptions discuss each of the PEAR DB module methods. Certain object and parameter names recur throughout the method descriptions in this appendix and have the following conventional meanings:

  • Connection object methods are called using a $conn object. The object is obtained by calling DB::connect().

  • Result object methods are called using a $result object. The object is obtained by calling a connection object method such as query() that generates a query result.

The method descriptions indicate data types for return values and parameters. A type of mixed indicates that a value might have different data types depending on how the value is used.

Square brackets ([]) in syntax descriptions indicate optional parameters. When an optional parameter is followed by = value, it indicates that if the parameter is omitted, value is its default value.

The examples print messages and query results as plain text for the most part. This is done to make the code easier to read. However, for scripts intended for execution in a Web environment, you generally should encode output with htmlspecialchars() if it may contain characters that are special in HTML, such as '<', '>', or '&'.

In the descriptions that follow, the term "SELECT statement" should be taken to mean a SELECT statement or any other statement that returns rows, such as DESCRIBE, EXPLAIN, or SHOW.

DB Class Methods

The DB class includes methods for connecting to the database server and for checking whether an object represents an error.

  • object
    connect (mixed $dsn
             [, array $options = array ()]);
    

    Connects to a database server. Returns a connection object if successful or a DB_Error error object if an error occurred.

    $dsn represents the data source name (DSN). The general DSN syntax takes this form:

    driver://user_name:password@host_name/db_name
    

    The driver value should be mysql or mysqli to select the DB mysql or mysqli drivers. mysql is the original MySQL driver and mysqli is the newer "MySQL improved" driver. mysql works with PHP 4 or 5. mysqli requires MySQL 4.1 or higher and PHP 5 or higher.

    The $options array, if given, provides additional connection options that are not specified in the DSN. See the description of the setOption() method for a list of allowable options.

    A connection object is a DB_common object returned by the particular database driver specified in the data source name.

    To close the connection, call the connection object disconnect() method.

    $conn =& DB::connect ("mysql://sampadm:secret@localhost/sampdb");
    if (DB::isError ($conn))
        die ("Could not connect\n");
    
    $conn->disconnect ();
    

  • boolean
    isError (mixed $value)
    

    Determines whether the value is a DB_Error object. Returns trUE if it is or FALSE otherwise.

    $conn =& DB::connect ("mysql://sampadm:secret@localhost/sampdb");
    if (DB::isError ($conn))
        die ("Could not connect\n");
    
    $result =& $conn->query ("SELECT COUNT(*) FROM member");
    if (DB::isError ($result))
        die ("Could not execute statement\n");
    

DB_common Object Methods

A DB_common object represents a connection to a database server. These objects have methods for constructing and executing SQL statements, controlling transactions, generating sequence values, and accessing PEAR DB configuration information.

Statement Construction and Execution Methods

The methods in this section are used for issuing SQL statements to the MySQL server. Each statement string must consist of a single statement, and should not end with a semicolon character (';') or a \g sequence. ';' and \g are conventions of the mysql client program and are not used when issuing queries through the PEAR DB interface.

  • integer
    affectedRows ()
    

    Returns the number of rows affected (modified) by the most recent DELETE, INSERT, REPLACE, or UPDATE statement on the given connection. Returns 0 for a SELECT statement. (Normally you use the numRows() result object method to determine the number of rows in a SELECT statement result set.) Returns a DB_Error object if an error occurred.

    $stmt = "INSERT INTO member (last_name,first_name,expiration)"
        . " VALUES('Brown','Marcia','2005-06-03')";
    if ($conn->query ($stmt) != DB_OK)
        die ("Statement failed\n");
    $count = $conn->affectedRows ();
    printf ("%d row%s inserted\n", $count, $count == 1 ? "" : "s");
    

  • integer
    autoExecute (string $tbl_name,
                 array $val_array
                 [, integer $mode = DB_AUTOQUERY_INSERT
                 [, string $where_clause = FALSE]])
    

    Generates and executes an INSERT or UPDATE statement for the table named by $tbl_name, based on the column name/value pairs in the $val_array associative array. Returns DB_OK for success or a DB_Error object if an error occurred.

    The $mode argument, if given, indicates whether to generate an INSERT or UPDATE statement. The allowable values are DB_AUTOQUERY_INSERT and DB_AUTOQUERY_UPDATE. The $where_clause argument, if given, should contain the text of a WHERE clause to be appended to the statement if it is an UPDATE. Any data values in this clause must be properly escaped.

    $params = array (
        "last_name" => "Brown",
        "first_name" => "Marcia",
        "expiration" => "2005-06-03"
    );
    if ($conn->autoExecute ("member", $params) != DB_OK)
        die ("Could not execute statement\n");
    

  • resource
    autoPrepare (string $tbl_name,
                 array $col_names,
                 [, integer $mode = DB_AUTOQUERY_INSERT
                 [, string $where_clause = FALSE]])
    

    Generates and prepares an INSERT or UPDATE statement for the table named by $tbl_name, based on the column names in the $col_names ordered array. Returns the prepared statement if successful or a DB_Error object if an error occurred.

    Data values for the columns in the statements should be represented by '?' placeholder markers. When you execute the prepared statement with the prepare() method, pass an array of parameter values to be bound to the placeholders. After you are done with the prepared statement, free it with freePrepared().

    The $mode argument, if given, indicates whether to generate an INSERT or UPDATE statement. The allowable values are DB_AUTOQUERY_INSERT and DB_AUTOQUERY_UPDATE. The $where_clause argument, if given, should contain the text of a WHERE clause to be appended to the statement if it is an UPDATE. Any data values in this clause must be properly escaped.

    $columns = array ("last_name", "first_name", "expiration");
    $params = array ("Brown", "Marcia", "2005-06-03");
    $prep_stmt = $conn->autoPrepare ("member", $columns);
    if (DB::isError ($prep_stmt))
        die ("Could not prepare statement\n");
    if ($conn->execute ($prep_stmt, $params) != DB_OK)
        die ("Could not execute statement\n");
    $conn->freePrepared ($prep_stmt);
    

  • boolean
    disconnect ()
    

    Close the connection to the database server. Returns trUE for success or FALSE if an error occurred.

    It's not required that you close a connection explicitly; PHP closes it automatically when the script terminates. On the other hand, if a script will execute for a while after it has finished accessing the MySQL server, closing the connection when you no longer need it is friendlier to the server, which then can reuse the connection for another client more quickly.

    $conn =& DB::connect ("mysql://sampadm:secret@localhost/sampdb");
    if (DB::isError ($conn))
        die ("Could not connect\n");
    
    $conn->disconnect ();
    

  • string
    escapeSimple (string $str)
    

    Performs simple-minded escaping of a string value so that it can be used as a literal data value in an SQL statement. Returns the resulting string.

    escapeSimple() does not properly handle NULL values and does not add quotes around string values. quoteSmart() does handle these values and for that reason generally is to be preferred to escapeSimple().

    $quoted_val1 = $conn->escapeSimple (13);
    $quoted_val2 = $conn->escapeSimple ("it's a string");
    

  • mixed
    execute (resource $prep_stmt
             [, mixed $params = array ()]))
    

    Executes the prepared statement given by $prep_stmt. The return value is like that for the query() method.

    The $params argument, if given, is an array of parameter values to be bound to any '?' placeholder markers in the statement. There must be one parameter in the array for each placeholder.

    $stmt = "INSERT INTO member (last_name,first_name,expiration)
        . " VALUES(?,?,?)";
    $prep_stmt = $conn->prepare ($stmt);
    if (DB::isError ($prep_stmt))
        die ("Could not prepare statement\n");
    $params = array ("Brown", "Marcia", "2005-06-03");
    if ($conn->execute ($prep_stmt, $params) != DB_OK)
        die ("Could not execute statement\n");
    $conn->freePrepared ($prep_stmt); 
    

  • mixed
    executeMultiple (resource $prep_stmt,
                     array $params_list)
    

    Executes the prepared statement given by $prep_stmt once for each member of the $params_list array. The return value is like that for the query() method.

    Each member of the $params_list array should itself be an array of parameter values to be bound to any '?' placeholder markers in the statement. There must be one parameter in the array for each placeholder.

    If statement execution fails for any set of parameter values, the remaining sets are not processed.

    $stmt = "INSERT INTO member (last_name,first_name,expiration)
        . " VALUES(?,?,?)";
    $prep_stmt = $conn->prepare ($stmt);
    if (DB::isError ($prep_stmt))
        die ("Could not prepare statement\n");
    $params_list = array (
        array ("Brown", "Marcia", "2005-06-03"),
        array ("O'Malley", "Brian", "2007-09-01"),
        array ("Green", "Spenser", "2006-11-15")
    );
    if ($conn->executeMultiple ($prep_stmt, $params_list) != DB_OK)
        die ("Could not execute statement\n");
    $conn->freePrepared ($prep_stmt);
    

  • boolean
    freePrepared (resource $prep_stmt)
    

    Frees resources associated with the given prepared statement. Returns trUE for success or FALSE if an error occurred.

    $stmt = "INSERT INTO member (last_name,first_name,expiration)
        . " VALUES(?,?,?)";
    $prep_stmt = $conn->prepare ($stmt);
    if (DB::isError ($prep_stmt))
        die ("Could not prepare statement\n");
    $params = array ("Brown", "Marcia", "2005-06-03");
    if ($conn->execute ($prep_stmt, $params) != DB_OK)
        die ("Could not execute statement\n");
    $conn->freePrepared ($prep_stmt);
    

  • array
    getAll (string $stmt
            [, array $params = array ()
            [, integer $mode = DB_FETCHMODE_DEFAULT]])
    

    Executes the statement given by $stmt, fetches the entire result set into an ordered array, and frees the result set. Returns the ordered array containing the result set or a DB_Error object if an error occurred. Each member of the result array contains one row of the result.

    The $params argument, if given, is an array of parameter values to be bound to any '?' placeholder markers in the statement. There must be one parameter in the array for each placeholder. The $mode argument, if given, indicates the row-fetching mode. The allowable values are the same as those that can be passed to setFetchMode().

    $row_list =& $conn->getAll ("SELECT last_name, first_name FROM member");
    if (DB::isError ($row_list))
        die ("Could not execute statement\n");
    

  • array
    getAssoc (string $stmt
              [, boolean $force_array = FALSE
              [, mixed $params = array ()
              [, integer $mode = DB_FETCHMODE_DEFAULT
              [, boolean $group = FALSE]]]])
    

    Executes the statement given by $stmt, fetches the result set into an associative array, and frees the result set. Returns the associative array containing the result set or a DB_Error object if an error occurred.

    The statement must select at least two columns. The associative array has elements keyed by the values of the first column of the result set. If the statement selects two columns, each element value consist of the second column value. If the statement selects more than two columns, each element value is an array containing those values from the columns following the first.

    The $force_array argument, if given and TRUE, forces element values to be arrays even if the statement selects only two columns. The $params argument, if given, is an array of parameter values to be bound to any '?' placeholder markers in the statement. There must be one parameter in the array for each placeholder. The $mode argument, if given, indicates the row-fetching mode. The allowable values are the same as those that can be passed to setFetchMode(). The $group argument, if given and trUE, is useful if the first column contains repeated values. It causes elements to be nested an extra level under the key values. That is, the element value for a given key is an ordered array, and the array members are the values from the rows that have the same key value. The easiest way to see the structure of the result is to print it with print_r(), as shown in the following example:

    $ary =& $conn->getAssoc ("SELECT last_name, first_name FROM member");
    if (DB::isError ($ary))
        die ("Could not execute statement\n");
    print_r ($ary);
    
    $ary =& $conn->getAssoc ("SELECT student_id, score FROM score",
                                FALSE, array(), DB_FETCHMODE_DEFAULT, TRUE);
    if (DB::isError ($ary))
        die ("Could not execute statement\n");
    print_r ($ary); 
    

  • array
    getCol (string $stmt
            [, mixed $col = 0
            [, mixed $params = array ()]])
    

    Executes the statement given by $stmt, fetches a column of the result set into an ordered array, and frees the result set. Returns the ordered array containing the column values or a DB_Error object if an error occurred.

    By default, this method fetches the first column of the result set. The $col argument, if given, indicates which column to fetch. Its value can be an integer column position (beginning at 0) or a string that specifies a column name. The $params argument, if given, is an array of parameter values to be bound to any '?' placeholder markers in the statement. There must be one parameter in the array for each placeholder.

    $col =& $conn->getCol ("SELECT last_name FROM member");
    if (DB::isError ($col))
        die ("Could not execute statement\n");
    print ("Member last names: " . join ("\n", $col) . "\n");
    

  • array
    getListOf (string $info_type)
    

    Returns information about the given $info_type as an ordered array. Returns the ordered array containing the information values or a DB_Error object if an error occurred.

    The allowable values of $info_type are "databases", "functions", "tables", "users", and "views", although the particular values that actually are supported depend on the database engine.

    $info =& $conn->getListOf ("databases");
    if (DB::isError ($info))
        die ("Cannot get list of databases");
    print ("Databases: " . join (" ", $info) . "\n");
    $info =& $conn->getListOf ("tables");
    if (DB::isError ($info))
        die ("Cannot get list of tables");
    print ("Tables in default database: " . join (" ", $info) . "\n");
    

  • mixed
    getOne (string $stmt
            [, mixed $params = array ()])
    

    Executes the statement given by $stmt, fetches the value in the first column of the first row of the result set, and frees the result set. Returns the value from the result set or a DB_Error object if an error occurred.

    The $params argument, if given, is an array of parameter values to be bound to any '?' placeholder markers in the statement. There must be one parameter in the array for each placeholder.

    $count =& $conn->getOne ("SELECT COUNT(*) FROM member");
    if (DB::isError ($count))
        die ("Could not execute statement\n");
    printf ("Number of members: %d\n", $count);
    

  • array
    getRow (string $stmt
            [, array $params = array ()
            [, integer $mode = DB_FETCHMODE_DEFAULT]])
    

    Executes the statement given by $stmt, fetches the first row of the result set into an ordered array, and frees the result set. Returns the ordered array containing the first row or a DB_Error object if an error occurred.

    The $params argument, if given, is an array of parameter values to be bound to any '?' placeholder markers in the statement. There must be one parameter in the array for each placeholder. The $mode argument, if given, indicates the row-fetching mode. The allowable values are the same as those that can be passed to setFetchMode().

    $row =& $conn->getRow ("SELECT * FROM member WHERE member_id = 2");
    if (DB::isError ($row))
        die ("Could not execute statement\n");
    print (join (",", $row) . "\n");
    

  • mixed
    limitQuery (string $stmt
                , integer $skip_count
                , integer $fetch_count,
                [, mixed $params = array ()])
    

    Executes the statement given by $stmt and fetches a subset of the rows, or modifies a subset of the rows. The return value is like that for the query() method.

    The $skip_count argument, if given, indicates how many initial rows to skip at the beginning of the result set. This value is used only for SELECT statements. The $fetch_count argument, if given, indicates how many rows to return for SELECT statements, or how many rows to modify for non-SELECT statements. The $params argument, if given, is an array of parameter values to be bound to any '?' placeholder markers in the statement. There must be one parameter in the array for each placeholder.

    $result =& $conn->limitQuery ("SELECT * FROM member", 10, 5);
    if (DB::isError ($result))
        die ("Could not execute statement\n");
    

  • resource
    prepare (string $stmt)
    

    Prepares the SQL statement given by $stmt for use by execute(). Returns the prepared statement or a DB_Error object if an error occurred.

    After you are done with the prepared statement, free it with freePrepared().

    $stmt = "INSERT INTO member (last_name,first_name,expiration) 
        . " VALUES(?,?,?)";
    $prep_stmt = $conn->prepare ($stmt);
    if (DB::isError ($prep_stmt))
        die ("Could not prepare statement\n");
    $params = array ("Brown", "Marcia", "2005-06-03");
    if ($conn->execute ($prep_stmt, $params) != DB_OK)
        die ("Could not execute statement\n");
    $conn->freePrepared ($prep_stmt);
    

  • boolean
    provides (string $feature_name)
    

    Determines whether the database engine (or the DB driver) supports a given feature. The $feature_name argument indicates which feature to check for. Returns trUE if the feature is available or FALSE if not.

    printf ("Database supports transactions: %s\n",
            $conn->provides ("transactions") ? "yes" : "no");
    

    The following table describes the allowable features.

    Feature

    Meaning

    limit

    Database supports LIMIT in SELECT statements

    pconnect

    Driver supports persistent connections

    prepare

    Database pre-checks prepared statements

    ssl

    Database supports secure connections using SSL

    transactions

    Database supports transactions


  • mixed
    query (string $stmt
           [, mixed $params = array ()])
    

    Executes the SQL statement given by $stmt and returns the result. For a successful non-SELECT statement such as INSERT or DELETE, the result is DB_OK. You can call affectedRows() to determine how many rows were modified. For a successful SELECT statement, the result is a DB_result object that you can use to obtain the data and metadata in the statement result. After you are done with the result object, you should invoke its free() method. For an error, the result is a DB_Error object.

    The $params argument, if given, is an array of parameter values to be bound to any '?' placeholder markers in the statement. There must be one parameter in the array for each placeholder.

    $result =& $conn->query ("SELECT last_name, first_name FROM member");
    if (DB::isError ($result))
        die ("Could not execute statement\n");
    /* ... process result set ... */
    $result->free ();
    if ($conn->query ("DELETE FROM member WHERE member_id = 149") != DB_OK)
        die ("Could not execute statement\n");
    

  • string
    quoteIdentifier (string $str)
    

    Quotes a string so that it can be used as an identifier such as a database, table, or column name. Returns the quoted string. This method should be used if the identifier contains characters that are not legal in unquoted identifiers.

    $ident = $conn->quoteIdentifier ("my column name");
    

  • mixed
    quoteSmart (mixed $value)
    

    Quotes a value so that it can be used as a literal data value in an SQL statement. Returns the quoted value. This method is used to make data values safe for insertion into statements. (An alternative is to use placeholder characters in the statement and bind data values to the statement when you execute it.)

    quoteSmart() handles the value according to its type. It returns numbers as unquoted numbers, strings as quoted strings with special characters properly escaped, and an argument of NULL as the unquoted string "NULL". For MySQL, quoteSmart() returns trUE or FALSE boolean values as 1 or 0.

    $quoted_val1 = $conn->quoteSmart (13);
    $quoted_val2 = $conn->quoteSmart ("it's a string");
    $quoted_val3 = $conn->quoteSmart (NULL);
    

  • void
    setFetchMode (integer $mode
                  [, string $obj_class = 'stdClass')
    

    Sets the default row-fetching mode. Returns nothing if successful or a DB_Error object if an error occurred.

    The allowable $mode values are as follows:

    • DB_FETCHMODE_ORDERED

      Returns each row as an ordered array. Column values are accessed as array elements, using numeric column indices in the range from 0 to numCols()1.

    • DB_FETCHMODE_ASSOC

      Returns each row as an associative array. Column values are accessed using associative indices corresponding to the names of the columns selected by the query from which the result set was generated.

    • DB_FETCHMODE_OBJECT

      Returns each row as an object. Column values are accessed as properties of the object. The property names are the names of the columns selected by the query from which the result set was generated.

    The default row-fetching mode is DB_FETCHMODE_ORDERED unless you change it with setFetchMode().

    The $obj_class argument, if given, can be DB_row to cause fetched rows to be stored in a new DB_row object.

    $err =& $conn->setFetchMode (DB_FETCHMODE_OBJECT);
    if (DB::isError ($err))
        die ("Could not set fetch mode\n");
    $result =& $conn->query ("SELECT last_name, first_name FROM president");
    if (DB::isError ($result))
        die ("Could not execute statement\n");
    while ($obj =& $result->fetchRow ())
        printf ("%s %s\n", $obj->last_name, $obj->first_name);
    $result->free ();
    

  • array
    tableInfo (mixed $result
               [, integer $mode = NULL])
    

    This method provides access to metadata about a table or query result. It returns an associative array if successful or a DB_Error object if an error occurred.

    By default, the result for a successful call is an array that contains one element per column of the table or query result. Element keys are column positions and element values are associative arrays containing metadata for the columns. Each column information array has the following keys:

    • table

      The table name.

    • name

      The column name.

    • type

      The column type. This will be one of the values listed in the following table. For a column calculated from an expression, the type value will reflect the expression type. A type value of "unknown" most likely indicates that the MySQL server is newer than the version of the MySQL client library that PHP is using and that the server knows about a new type the library doesn't recognize.

      Value

      Data Type of Column

      blob

      BLOB (or TEXT) column

      date

      DATE column

      datetime

      DATETIME column

      int

      Integer numeric column

      null

      Column containing only NULL values

      real

      Floating-point numeric column

      string

      String column other than BLOB or TEXT

      time

      TIME columns

      timestamp

      TIMESTAMP column

      unknown

      Unknown data type

      year

      YEAR column


    • len

      The column display width or string length.

    • flags

      The column flags. This is a string containing a space-separated list of words indicating which of a column's flag values are true. For flags that are false, the corresponding word is not present in the string. The following table lists the possible flag values.

      Value

      Meaning

      auto_increment

      Column has the AUTO_INCREMENT attribute

      binary

      Column has the BINARY attribute

      blob

      Column is a BLOB or TEXT type

      enum

      Column is an ENUM

      multiple_key

      Column is a part of a non-unique index

      not_null

      Column cannot contain NULL values

      primary_key

      Column is a part of a PRIMARY KEY

      timestamp

      Column is a TIMESTAMP

      unique_key

      Column is a part of a UNIQUE index

      unsigned

      Column has the UNSIGNED attribute

      zerofill

      Column has the ZEROFILL attribute


      The meaning of the "binary" flag is that the column contains binary strings.

      To access the individual words of a flags value, split it with explode(). For example:

      $words = explode (" ", $info[$col_num]["flags"]);
      

    The $mode argument, if given, determines how much information the result contains:

    • NULL or 0 produce the default result.

    • DB_TABLEINFO_ORDER adds two elements to the default result. The first has a key of "num_fields" and value of the number of columns in the table or query result. The second has a key of "order" and the value is an associative array that maps column names to position within the table or query result.

    • DB_TABLEINFO_ORDERTABLE adds to the default result the "num_fields" element and an "order_table" element that is similar to the "order" element, except that it contains one element per table.

    • DB_TABLEINFO_FULL is equivalent to the combination of DB_TABLEINFO_ORDER and DB_TABLEINFO_ORDERTABLE.

    The easiest way to see the structure of a result from tableInfo() is to print it with print_r(), as shown in the following example:

    # Get information about table
    $info =& $conn->tableInfo ("member");
    if (DB::isError ($info))
        die ("Cannot get member table metadata");
    print_r ($info);
    # Get information about query result
    $result =& $conn->query ("SELECT last_name, first_name FROM member");
    if (DB::isError ($result))
        die ("Could not execute statement\n");
    $info =& $conn->tableInfo ($result, DB_TABLEINFO_ORDER);
    if (DB::isError ($info))
        die ("Cannot get query result metadata");
    print_r ($info);
    $result->free ();
    

Transaction Control Methods

The connection object methods in this section provide control over transaction processing. The following example shows one way to use them:

if ($conn->autoCommit (FALSE) == DB_OK) # disable autocommit mode
{
    if ($conn->query ($stmt1) == DB_OK && $conn->query ($stmt2) == DB_OK)
        $conn->commit ();               # commit if successful
    else
        $conn->rollback ();             # roll back if unsuccessful
    $conn->autoCommit (TRUE);           # re-enable autocommit mode
}

  • mixed
    autoCommit ([boolean $mode = FALSE]
    

    Sets the autocommit mode to trUE (enabled) or FALSE (disabled). Returns DB_OK for success or a DB_Error object if an error occurred.

  • mixed
    commit ()
    

    Commits the current transaction. Returns DB_OK for success or a DB_Error object if an error occurred.

  • mixed
    rollback ()
    

    Rolls back the current transaction. Returns DB_OK for success or a DB_Error object if an error occurred.

Sequence Generation Methods

The methods in this section are used to generate sequence values.

  • integer
    createSequence (string $seq_name)
    

    Creates a new sequence using the name given by $seq_name. Returns DB_OK for success or a DB_Error object if an error occurred.

    For MySQL, what actually happens is that the DB module creates a table with an AUTO_INCREMENT column. The table name is $seq_name with "_seq" added to it. For example, if $seq_name is "seqnum", the sequence table name is seqnum_seq. The format string used for creating sequence table names can be changed with the setOption() connection object method.

    $err = $conn->createSequence ("seqnum");
    if (DB::isError ($err))
        die ("Could not create sequence\n");
    

  • integer
    dropSequence (string $seq_name)
    

    Drops the sequence having the name given by $seq_name. Returns DB_OK for success or a DB_Error object if an error occurred.

    $id = $conn->nextId ("seqnum");
    if (DB::isError ($id))
        die ("Could not generate next sequence number\n");
    

  • resource
    nextId (string $seq_name
            [, boolean $auto_create = TRUE])
    

    Generates the next number in the sequence having the name given by $seq_name. Returns the integer sequence value for success or a DB_Error object if an error occurred.

    The optional $auto_create argument indicates whether to create the sequence automatically if it does not already exist. The default is to do so.

    $err = $conn->dropSequence ("seqnum");
    if (DB::isError ($err))
        die ("Could not drop sequence\n");
    

Information Methods

The methods in this section provide access to PEAR DB configuration information.

  • mixed
    getOption (string $opt_name)
    

    Gets the value of a runtime PEAR DB configuration option named $opt_name. The type of the return value depends on the option. See the description of the setOption() method for a list of allowable option names.

    print ("seqname_format: " . $conn->getOption ("seqname_format") . "\n");
    

  • integer
    setOption (string $opt_name, mixed $value)
    

    Sets a runtime PEAR DB configuration option named $opt_name to the value given by $value. Returns DB_OK if successful or a DB_Error object if an error occurred.

    if ($conn->setOption ("autofree", TRUE) != DB_OK)
        print ("Could not set autofree option\n");
    

    The following table lists the allowable options:

    Option

    Type

    Default Value

    Description

    autofree

    boolean

    FALSE

    Whether to free results automatically

    debug

    integer

    0

    Debugging level

    persistent

    boolean

    FALSE

    Whether to use persistent connections

    portability

    integer

    DB_PORTABILITY_NONE

    The portability mode

    seqname_format

    string

    %s_seq

    sprintf() format string for sequence names

    ssl

    boolean

    FALSE

    Whether to connect using SSL


DB_result Object Methods

A DB_result object provides access to information about statement results. Such results are available for statements such as SELECT that produce a result set, not for statements such as INSERT or DELETE that produce only a status.

You can also pass a result object to the tableInfo() connection object method to obtain additional result metadata.

  • integer
    fetchInto (mixed &$var
               [, integer $mode = DB_FETCHMODE_DEFAULT
               [, integer $row_num = NULL]]);
    

    Fetches a row of the result set into a value and advances the row pointer to the next row. Returns DB_OK if successful, NULL if there are no more rows, or a DB_Error object if an error occurred.

    The $mode argument, if given, indicates the type of value to place in the variable. The allowable values are the same as those that can be passed to setFetchMode(). The $row_num argument, if given, indicates which row to fetch. The first row is numbered 0.

    $result =& $conn->query ("SELECT last_name, first_name FROM president");
    if (DB::isError ($result))
        die ("Could not execute statement\n");
    while ($result->fetchInto ($row))
        printf ("%s %s\n", $row[0], $row[1]);
    $result->free ();
    

  • mixed
    fetchRow ([integer $mode = DB_FETCHMODE_DEFAULT
              [, integer $row_num = NULL]]);
    

    Fetches a row of the result set into a value and advances the row pointer to the next row. Returns the next row if successful, NULL if there are no more rows, or a DB_Error object if an error occurred.

    The $mode argument, if given, indicates the row-fetching mode. The allowable values are the same as those that can be passed to setFetchMode(). The $row_num argument, if given, indicates which row to fetch. The first row is numbered 0.

    $result =& $conn->query ("SELECT last_name, first_name FROM president");
    if (DB::isError ($result))
        die ("Could not execute statement\n");
    while ($row =& $result->fetchRow ())
        printf ("%s %s\n", $row[0], $row[1]);
    $result->free ();
    

  • boolean
    free ()
    

    Discards the result set and releases any memory associated with it. Does not discard the result set object itself. Returns trUE for success or FALSE if an error occurred.

    $result =& $conn->query ("SELECT last_name, first_name FROM member");
    if (DB::isError ($result))
        die ("Could not execute statement\n");
    /* ... process result set ... */
    $result->free ();
    

  • integer
    numCols ()
    

    Returns the number of columns in the result set or a DB_Error object if an error occurred.

    $result =& $conn->query ("SELECT * FROM president");
    if (DB::isError ($result))
        die ("Could not execute statement\n");
    printf ("Number of columns: %d\n", $result->numCols ());
    $result->free ();
    

  • integer
    numRows ()
    

    Returns the number of rows in the result set or a DB_Error object if an error occurred.

    $result =& $conn->query ("SELECT * FROM president");
    if (DB::isError ($result))
        die ("Could not execute statement\n");
    printf ("Number of rows: %d\n", $result->numRows ());
    $result->free ();
    

DB_Error Object Methods

The error object methods in this section provide information about the error represented by the object:

$result =& $conn->query ($stmt);
if (DB::isError ($result))
{
    print ("     getCode value: " . $result->getCode() . "\n");
    print ("  getMessage value: " . $result->getMessage() . "\n");
    print (" getUserInfo value: " . $result->getUserInfo() . "\n");
}

There are other methods available in addition to those listed here. See the description of the PEAR_Error class in the PEAR manual.

  • integer
    getCode ()
    

    Returns an integer containing the error code.

  • string
    getMessage ()
    

    Returns a string containing the error message.

  • string
    getUserInfo ()
    

    Returns a string containing additional information about the error.

    Team LiB
    Previous Section Next Section