cvs: peardoc /en/package/database/mdb2 intro-auto.xml intro-connect.xml intro-dsn.xml intro-execute.xml intro-fetch.xml intro-portability.xml
intro-query.xml intro-sequences.xml
| From: | Lukas Smith | Date: | Sun, 30 Apr 2006 20:26:15 +0000 |
| Subject: | cvs: peardoc /en/package/database/mdb2 intro-auto.xml intro-connect.xml intro-dsn.xml intro-execute.xml intro-fetch.xml intro-portability.xml intro-query.xml intro-sequences.xml |
||
| Groups: | php.pear.doc | ||
| Request: | Send a blank email to pear-doc+get-7852@lists.php.net to get a copy of this message | ||
lsmith Sun Apr 30 20:26:15 2006 UTC
Added files:
/peardoc/en/package/database/mdb2 intro-auto.xml intro-connect.xml
intro-dsn.xml intro-execute.xml
intro-fetch.xml
intro-portability.xml
intro-query.xml
intro-sequences.xml
Log:
- initial port from DB .. still not complete content-wise and URL's probably need to be
changed to entities or something ..
http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-auto.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-auto.xml +++ peardoc/en/package/database/mdb2/intro-auto.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <!-- needs fixing for MDB2--> <refentry id="package.database.mdb2.intro-auto"> <refnamediv> <refname>Introduction - autoPrepare & autoExecute</refname> <refpurpose>Automatically prepare and execute SQL statements</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-auto.desc"> &title.desc; <refsect2> <title>Purpose</title> <para> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoprepare"> <function>autoPrepare</function></link> and <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoexecute"> <function>autoExecute</function></link> reduce the need to write boring <command>INSERT</command> or <command>UPDATE</command> SQL queries which are difficult to maintain when you add a field for instance. </para> <para> Imagine you have a 'user' table with 3 fields (id, name and country). You have to write sql queries like: <programlisting role="sql"> <![CDATA[ INSERT INTO table (id, name, country) VALUES (?, ?, ?) UPDATE table SET id=?, name=?, country=? WHERE ... ]]> </programlisting> If you add a field ('birthYear' for example), you have to rewrite your queries which is boring and can lead to bugs (if you forget one query for instance). </para> </refsect2> <refsect2> <title>autoPrepare</title> <para> With <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoprepare"> <function>autoPrepare</function></link>, you don't have to write your insert or update queries. For example: <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $table_name = 'user'; $table_fields = array('id', 'name', 'country'); $sth = $mdb2->autoPrepare($table_name, $table_fields, MDB2_AUTOQUERY_INSERT); if (PEAR::isError($sth)) { die($sth->getMessage()); } ?> ]]> </programlisting> In this example, <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoprepare"> <function>autoPrepare</function></link> will build the following SQL query: <programlisting role="sql"> <![CDATA[ INSERT INTO user (id, name, country) VALUES (?, ?, ?) ]]> </programlisting> And then, it will call <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare"> <function>prepare</function></link> with it. </para> <para> To add records, you have to use <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodexecute"> <function>execute</function></link> or <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodexecutemultiple"> <function>executeMultiple</function></link> like: <programlisting role="php"> <![CDATA[ <?php // ... contining from the example above... $table_values = array(1, 'Fabien', 'France'); $res =& $mdb2->execute($sth, $table_values); if (PEAR::isError($res)) { die($res->getMessage()); } ?> ]]> </programlisting> So, you don't have to write any SQL <command>INSERT</command> queries! And it works with <command>UPDATE</command> queries too. For flexibility reasons, you have only to write the <command>WHERE</command> clause of the query. For instance: <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $table_name = 'user'; $table_fields = array('name', 'country'); $table_values = array('Bob', 'USA'); $sth = $mdb2->autoPrepare($table_name, $table_fields, MDB2_AUTOQUERY_UPDATE, 'id = 1'); if (PEAR::isError($sth)) { die($sth->getMessage()); } $res =& $mdb2->execute($sth, $table_values); if (PEAR::isError($res)) { die($res->getMessage()); } ?> ]]> </programlisting> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoprepare"> <function>autoPrepare</function></link> will build the following query: <programlisting role="sql"> <![CDATA[ UPDATE user SET name=?, country=? WHERE id=1 ]]> </programlisting> Then, it will call <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare"> <function>prepare</function></link> with it. </para> <para> Be careful, if you don't specify any <command>WHERE</command> clause, all the records of the table will be updated. </para> </refsect2> <refsect2> <title>autoExecute</title> <para> Using <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoexecute"> <function>autoExecute</function></link> is the easiest way to do insert or update queries. It is a mix of <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoprepare"> <function>autoPrepare</function></link> and <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoprepare"> <function>execute</function></link>. </para> <para> You only need an associative array (key => value) where keys are fields names and values are corresponding values of these fields. For instance: <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $table_name = 'user'; $fields_values = array( 'id' => 1, 'name' => 'Fabien', 'country' => 'France' ); $res = $mdb2->autoExecute($table_name, $fields_values, MDB2_AUTOQUERY_INSERT); if (PEAR::isError($res)) { die($res->getMessage()); } ?> ]]> </programlisting> And that's all! The following query is built and executed: <programlisting role="sql"> <![CDATA[ INSERT INTO user (id, name, country) VALUES (1, 'Fabien', 'France') ]]> </programlisting> </para> <para> And it's the same thing for <command>UPDATE</command> queries: <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $table_name = 'user'; $fields_values = array( 'name' => 'Fabien', 'country' => 'France' ); $res = $mdb2->autoExecute($table_name, $fields_values, MDB2_AUTOQUERY_UPDATE, 'id = 1'); if (PEAR::isError($res)) { die($res->getMessage()); } ?> ]]> </programlisting> which prepares and executes the following query: <programlisting role="sql"> <![CDATA[ UPDATE user SET name='Fabien', country='France' WHERE id = 1 ]]> </programlisting> </para> <para> Be careful, if you don't specify any <command>WHERE</command> statement, all the records of the table will be updated. </para> <warning> <para> The values passed in <parameter>$data</parameter> must be literals. Do not submit SQL functions (for example <literal>CURDATE()</literal>). SQL functions that should be performed at execution time need to be put in the prepared statement. </para> </warning> </refsect2> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-connect.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-connect.xml +++ peardoc/en/package/database/mdb2/intro-connect.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <!-- add information on the following methods: factory(), singleton() --> <refentry id="package.database.mdb2.intro-connect"> <refnamediv> <refname>Introduction - Connect</refname> <refpurpose>Connecting and disconnecting a database</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-connect.desc"> &title.desc; <para> To connect to a database you have to use the function <link linkend="package.database.mdb2.db.connect"> <function>connect</function></link>, which requires a valid <link linkend="package.database.mdb2.intro-dsn">DSN</link> as the first parameter. This parameter can either be a string or an array. If using an array, the array used gets merged with the default information: <programlisting role="configuration"> <![CDATA[ $dsn = array( 'phptype' => false, 'dbsyntax' => false, 'username' => false, 'password' => false, 'protocol' => false, 'hostspec' => false, 'port' => false, 'socket' => false, 'database' => false, 'new_ink' => false, ); ]]> </programlisting> Any elements you set override the defaults and the remainder stay at their defaults. </para> <simpara> The second parameter is the optional <parameter>$options</parameter> array that can contain runtime configuration settings for this package. See <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodsetOption"> <function>setOption</function></link> for more information on the available settings. </simpara> <simpara> In case of success you get a new instance of the database class. It is strongly recommened to check this return value with <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2.html#methodisError"> <function>isError</function></link>. </simpara> <simpara> To disconnect use the method <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methoddisconnect"> <function>disconnect</function></link> from your database class instance. </simpara> <example> <title>Connect and disconnect</title> <programlisting role="php"> <![CDATA[ <?php require_once 'MDB2.php'; $dsn = 'pgsql://someuser:apasswd@localhost/thedb'; $options = array( 'debug' => 2, 'result_buffering' => false, ); $mdb2 =& MDB2::connect($dsn, $options); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } // ... $mdb2->disconnect(); ?> ]]> </programlisting> </example> <example> <title>Connect using an array for the DSN information</title> <programlisting role="php"> <![CDATA[ <?php require_once 'MDB2.php'; $dsn = array( 'phptype' => 'pgsql', 'username' => 'someuser', 'password' => 'apasswd', 'hostspec' => 'localhost', 'database' => 'thedb', ); $options = array( 'debug' => 2, 'portability' => MDB2_PORTABILITY_ALL, ); $mdb2 =& MDB2::connect($dsn, $options); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } ?> ]]> </programlisting> <para> When connecting to SQLite using a DSN array, the value of the <varname>mode</varname> element must be a string: <programlisting role="php"> <![CDATA[ <?php $dsn = array( 'phptype' => 'sqlite', 'database' => 'thedb', 'mode' => '0644', ); ?> ]]> </programlisting> </para> </example> <example> <title> Connect to MySQLi via SSL using an array for the DSN information </title> <para> The <varname>ssl</varname> element of the <parameter>$options</parameter> array must be set to &true; in order for SSL to work. Each of the extra elements in the <parameter>$dsn</parameter> array (<varname>key</varname> through <varname>cipher</varname> in the example below) are optional. </para> <programlisting role="php"> <![CDATA[ <?php require_once 'MDB2.php'; $dsn = array( 'phptype' => 'mysqli', 'username' => 'someuser', 'password' => 'apasswd', 'hostspec' => 'localhost', 'database' => 'thedb', 'key' => 'client-key.pem', 'cert' => 'client-cert.pem', 'ca' => 'cacert.pem', 'capath' => '/path/to/ca/dir', 'cipher' => 'AES', ); $options = array( 'ssl' => true, ); $mdb2 =& MDB2::connect($dsn, $options); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } ?> ]]> </programlisting> </example> <example> <title>Connect to a PostgreSQL database via a socket</title> <programlisting role="php"> <![CDATA[ <?php require_once 'MDB2.php'; $dsn = 'pgsql://someuser:apasswd@unix(/tmp)/thedb'; $options = array( 'debug' => 2, 'portability' => MDB2_PORTABILITY_ALL, ); $mdb2 =& MDB2::connect($dsn, $options); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } ?> ]]> </programlisting> </example> </refsect1> <refsect1 id="package.database.mdb2.db-common.intro-connect.see"> &title.see; <para> <link linkend="package.database.mdb2.intro-portability"> <quote>Intro - Portability</quote></link> </para> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-dsn.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-dsn.xml +++ peardoc/en/package/database/mdb2/intro-dsn.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <refentry id="package.database.mdb2.intro-dsn"> <refnamediv> <refname>Introduction - DSN</refname> <refpurpose>The Data Source Name</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-dsn.desc"> &title.desc; <simpara> To connect to a database through PEAR::MDB2, you have to create a valid <acronym>DSN - data source name</acronym>. This DSN consists in the following parts: </simpara> <para> <simplelist> <member> <varname>phptype</varname>: Database backend used in PHP (i.e. <literal>mysql</literal> , <literal>pgsql</literal> etc.) </member> <member> <varname>dbsyntax</varname>: Database used with regards to SQL syntax etc. </member> <member> <varname>protocol</varname>: Communication protocol to use ( i.e. <literal>tcp</literal>, <literal>unix</literal> etc.) </member> <member> <varname>hostspec</varname>: Host specification (<literal>hostname[:port]</literal>) </member> <member> <varname>database</varname>: Database to use on the DBMS server </member> <member> <varname>username</varname>: User name for login </member> <member> <varname>password</varname>: Password for login </member> <member> <varname>proto_opts</varname>: Maybe used with <varname>protocol</varname> </member> <member> <varname>option</varname>: Additional connection options in URI query string format. options get separated by & </member> </simplelist> </para> <para> The DSN can either be provided as an associative array or as a string. The string format of the supplied DSN is in its fullest form: <programlisting role="url"> <![CDATA[ phptype(dbsyntax)://username:password@protocol+hostspec/database?option=value ]]> </programlisting> </para> <para> Most variations are allowed: <programlisting role="url"> <![CDATA[ phptype://username:password@protocol+hostspec:110//usr/db_file.db phptype://username:password@hostspec/database phptype://username:password@hostspec phptype://username@hostspec phptype://hostspec/database phptype://hostspec phptype:///database phptype:///database?option=value&anotheroption=anothervalue phptype(dbsyntax) phptype ]]> </programlisting> </para> <para> The currently supported database backends are: <programlisting role="configure"> <![CDATA[ fbsql -> FrontBase ibase -> InterBase (requires PHP 5) mssql -> Microsoft SQL Server (NOT for Sybase. Compile PHP --with-mssql) mysql -> MySQL (for MySQL <= 4.0) mysqli -> MySQL (for MySQL >= 4.1) (requires PHP 5) oci8 -> Oracle 7/8/9 pgsql -> PostgreSQL querysim -> QuerySim sqlite -> SQLite ]]> </programlisting> </para> <para> A second DSN format is supported <programlisting role="url"> <![CDATA[ phptype(syntax)://user:pass@protocol(proto_opts)/database ]]> </programlisting> </para> <para> If your <varname>database</varname>, <varname>option</varname> values, <varname>username</varname> or <varname>password</varname> contain characters used to delineate DSN parts, you can escape them via URI hex encodings: <programlisting role="url"> <![CDATA[ : = %3a / = %2f @ = %40 + = %2b ( = %28 ) = %29 ? = %3f = = %3d & = %26 ]]> </programlisting> </para> <warning> <para> Please note, that some features may be not supported by all database backends. </para> </warning> </refsect1> <refsect1 id="package.database.mdb2.intro-dsn.example"> &title.example; <example> <title>Connect to database through a socket</title> <programlisting role="url"> <![CDATA[ mysql://user@unix(/path/to/socket)/pear ]]> </programlisting> </example> <example> <title>Connect to database on a non standard port</title> <programlisting role="url"> <![CDATA[ pgsql://user:pass@tcp(localhost:5555)/pear ]]> </programlisting> </example> <example> <title>Connect to SQLite on a Unix machine using options</title> <programlisting role="url"> <![CDATA[ sqlite:////full/unix/path/to/file.db?mode=0666 ]]> </programlisting> </example> <example> <title>Connect to SQLite on a Windows machine using options</title> <programlisting role="url"> <![CDATA[ sqlite:///c:/full/windows/path/to/file.db?mode=0666 ]]> </programlisting> </example> <example> <title>Connect to MySQLi using SSL</title> <programlisting role="url"> <![CDATA[ mysqli://user:pass@localhost/pear?key=client-key.pem&cert=client-cert.pem ]]> </programlisting> </example> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-execute.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-execute.xml +++ peardoc/en/package/database/mdb2/intro-execute.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <!-- needs fixing for MDB2--> <refentry id="package.database.mdb2.intro-execute"> <refnamediv> <refname>Introduction - Prepare & Execute</refname> <refpurpose>Prepare and execute SQL statements</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-execute.desc"> &title.desc; <refsect2 id="package.database.mdb2.intro-execute.desc.purpose"> <title>Purpose</title> <para> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare"> <function>prepare</function></link> and <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodexecute"> <function>execute*</function></link> give you more power and flexibilty for query execution. Prepare/execute mode is helpful when you have to run the same query several times but with different values in it, such as adding a list of addresses into a database. </para> <para> Another place prepare/execute is useful is supporting databases which have different SQL syntaxes. Imagine you want to support two databases with different <command>INSERT</command> syntax: <programlisting> <![CDATA[ db1: INSERT INTO tbl_name (col1, col2) VALUES (expr1, expr2) db2: INSERT INTO tbl_name SET col1=expr1, col2=expr2 ]]> </programlisting> Correspondending to create multi-lingual scripts you can create a array with queries like this: <programlisting role="php"> <![CDATA[ $statement['db1']['INSERT_PERSON'] = 'INSERT INTO person (surname, name, age) VALUES (?, ?, ?)'; $statement['db2']['INSERT_PERSON'] = 'INSERT INTO person SET surname=?, name=?, age=?'; ]]> </programlisting> </para> </refsect2> <refsect2 id="package.database.mdb2.intro-execute.desc.prepare"> <title>Prepare</title> <para> To use the features above, you have to do two steps. Step one is to <emphasis>prepare</emphasis> the statement and the second is to <emphasis>execute</emphasis> it. </para> <para> To start out, you need to <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare"> <function>prepare</function></link> a generic SQL statment. Create a generic statment by writing the SQL query as usual: <programlisting role="sql"> <![CDATA[ SELECT surname, name, age FROM person WHERE name = 'name_to_find' AND age < age_limit ]]> </programlisting> Then substitute <quote>placeholders</quote> for the literal values which will be provided at run time: <programlisting role="sql"> <![CDATA[ SELECT surname, name, age FROM person WHERE name = ? AND age < ? ]]> </programlisting> Then pass this SQL statement to <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare"> <function>prepare</function></link>, which returns a statement handle to be used when calling <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodexecute"> <function>execute</function></link>. </para> <para> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare"> <function>prepare</function></link> can handle different types of placeholders (a.k.a. wildcards). <simplelist> <member> <literal>?</literal> - (recommended) stands for a scalar value like strings or numbers. The value will be automatically escaped and quoted according to the current DBMS's requirements. </member> <member> <literal>!</literal> - stands for a scalar value and will inserted into the statement <quote>as is</quote>. </member> <member> <literal>&</literal> - requires an existing filename, the content of this file will be included into the statment (i.e. for saving binary data of a graphic file in a database) </member> </simplelist> </para> <para> Use backslashes to escape placeholder characters if you don't want them to be interpreted as placeholders: <programlisting role="sql"> <![CDATA[ UPDATE foo SET col=? WHERE col='over \& under' ]]> </programlisting> </para> </refsect2> <refsect2 id="package.database.mdb2.intro-execute.desc.execute"> <title>Execute</title> <para> After preparing the statement, you can execute the query. This means to assign the variables to the prepared statement. To do this, <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodexecute"> <function>execute</function></link> requires two arguments: the statement handle returned by <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare"> <function>prepare</function></link> and a scalar or array with the values to assign. </para> <para> <example> <title>Passing scalars to <function>execute</function></title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $sth = $mdb2->prepare('INSERT INTO numbers (number) VALUES (?)'); $mdb2->execute($sth, 1); $mdb2->execute($sth, 8); ?> ]]> </programlisting> </example> </para> <para> When a prepared statement has multiple placeholders, you must use an array to pass the values to <function>execute</function>. The first entry of the array represents the first placeholder, the second the second placeholder, etc. The order is independent of the type of placeholder used. </para> <para> <example> <title>Passing an array to <function>execute</function></title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $sth = $mdb2->prepare('INSERT INTO numbers VALUES (?, ?, ?)'); $data = array(1, 'one', 'en'); $mdb2->execute($sth, $data); ?> ]]> </programlisting> </example> </para> <warning> <para> The values passed in <parameter>$data</parameter> must be literals. Do not submit SQL functions (for example <literal>CURDATE()</literal>). SQL functions that should be performed at execution time need to be put in the prepared statement. Similarly, identifiers (i.e. table names and column names) can not be used because the names get validated during the prepare phase. </para> </warning> </refsect2> <refsect2 id="package.database.mdb2.intro-execute.desc.executemultiple"> <title>ExecuteMultiple</title> <para> MDB2 contains a process for executing several queries at once. So, rather than having to execute them manually, like this: <example> <title>Passing arrays to <function>execute</function></title> <programlisting role="php"> <![CDATA[ // Once you have a valid MDB2 object named $mdb2... $alldata = array(array(1, 'one', 'en'), array(2, 'two', 'to'), array(3, 'three', 'tre'), array(4, 'four', 'fire')); $sth = $mdb2->prepare('INSERT INTO numbers VALUES (?, ?, ?)'); foreach ($alldata as $row) { $mdb2->execute($sth, $row); } ]]> </programlisting> </example> which would issue four queries: <programlisting role="sql"> <![CDATA[ INSERT INTO numbers VALUES ('1', 'one', 'en') INSERT INTO numbers VALUES ('2', 'two', 'to') INSERT INTO numbers VALUES ('3', 'three', 'tre') INSERT INTO numbers VALUES ('4', 'four', 'fire') ]]> </programlisting> you can use <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodexecutemultiple"> <function>executeMultiple</function></link> to avoid the explicit foreach in the eample above: <example> <title> Using <function>executeMultiple</function> instead of <function>execute</function> </title> <programlisting role="php"> <![CDATA[ // Once you have a valid MDB2 object named $mdb2... $alldata = array(array(1, 'one', 'en'), array(2, 'two', 'to'), array(3, 'three', 'tre'), array(4, 'four', 'fire')); $sth = $mdb2->prepare('INSERT INTO numbers VALUES (?, ?, ?)'); $mdb2->executeMultiple($sth, $alldata); ]]> </programlisting> </example> </para> <para> The result is the same. If one of the records failed, the unfinished records will not be executed. </para> <para> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodexecute"> <function>execute*</function></link> has three possible returns: a new MDB2_Result_Common object for queries that return results (such as <command>SELECT</command> queries), &constant.db-ok; for queries that manipulate data (such as <command>INSERT</command> queries) or a MDB2_Error object on failure </para> </refsect2> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-fetch.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-fetch.xml +++ peardoc/en/package/database/mdb2/intro-fetch.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <!-- add information on the following methods: seek(), getResource(), bindColumn(), setResultTypes() and nextResult() --> <refentry id="package.database.mdb2.intro-fetch"> <refnamediv> <refname>Introduction - Results</refname> <refpurpose>Obtaining data from query results</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-fetch.desc"> &title.desc; <refsect2 id="package.database.mdb2.intro-fetch.desc.fetch"> <title>Fetching Individual Rows From Query Results</title> <para> The MDB2_Result_Common object provides two methods for fetching data from rows of a result set: <link linkend="http://pear.php.net/package/MDB2/docs/latest/apidoc/MDB2/MDB2_Result_Common.html#methodfetchOne"> <function>fetchOne</function></link>, <link linkend="http://pear.php.net/package/MDB2/docs/latest/apidoc/MDB2/MDB2_Result_Common.html#methodfetchRow"> <function>fetchRow</function></link>, <link linkend="http://pear.php.net/package/MDB2/docs/latest/apidoc/MDB2/MDB2_Result_Common.html#methodfetchCol"> <function>fetchCol</function></link> and <link linkend="http://pear.php.net/package/MDB2/docs/latest/apidoc/MDB2/MDB2_Result_Common.html#methodfetchAll"> <function>fetchAll</function></link>. </para> <para> <function>fetchRow</function> and <function>fetchOne</function> read an entire row or a single column respectively. The result pointer gets moved to the next row each time these methods are called. &null; is returned when the end of the result set is reached. </para> <para> <function>fetchRow</function> reads an entire row as an array and <function>fetchOne</function> reads an single column into a scalar. The result pointer gets moved to the next row each time these methods are called. &null; is returned when the end of the result set is reached. </para> <para> MDB2_Error is returned if an error is encountered. </para> <example> <title>Fetching a result set</title> <programlisting role="php"> <![CDATA[ <?php // Create a valid MDB2 object named $mdb2 // at the beginning of your program... require_once 'MDB2.php'; $mdb2 =& MDB2::connect('pgsql://usr:pw@localhost/dbnam'); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } // Proceed with getting some data... $res =& $mdb2->query('SELECT * FROM mytable'); // Get each row of data on each iteration until // there are no more rows while (($row = $res->fetchRow())) { // Assuming MDB2's default fetchmode is MDB2_FETCHMODE_ORDERED echo $row[0] . "\n"; } // while (($one = $res->fetchOne())) { // echo $one . "\n"; // } ?> ]]> </programlisting> </example> </refsect2> <refsect2 id="package.database.mdb2.intro-fetch.desc.format"> <title>Formats of Fetched Rows</title> <para> The data from the row of a query result can be placed into one of three constructs: an ordered array (with column numbers as keys), an associative array (with column names as keys) or an object (with column names as properties). </para> <para> <constant>MDB2_FETCHMODE_ORDERED</constant> (default) <screen> <![CDATA[ Array ( [0] => 28 [1] => hi ) ]]> </screen> </para> <para> <constant>MDB2_FETCHMODE_ASSOC</constant> <screen> <![CDATA[ Array ( [a] => 28 [b] => hi ) ]]> </screen> </para> <para> <constant>MDB2_FETCHMODE_OBJECT</constant> <screen> <![CDATA[ stdClass Object ( [a] => 28 [b] => hi ) ]]> </screen> </para> <para> NOTE: When a query contains the same column name more than once (such as when joining tables which have duplicate column names) and the fetch mode is <constant>MDB2_FETCHMODE_ASSOC</constant> or <constant>MDB2_FETCHMODE_OBJECT</constant>, the data from the last column with a given name will be the one returned. There are two immediate options to work around this issue: <simplelist> <member> Use aliases in your query, for example <userinput>People.Name AS PersonName</userinput> </member> <member> Change the fetch mode to <constant>MDB2_FETCHMODE_ORDERED</constant> </member> </simplelist> </para> <para> TIP: If you are running into this issue, it likely indicates poor planning of the database schema. Either data is needlessly being duplicated or the same names are being used for different kinds of data. </para> </refsect2> <refsect2 id="package.database.mdb2.intro-fetch.desc.set"> <title>How to Set Formats</title> <para> You can set the fetch mode each time you call a fetch method and/or you can set the default fetch mode for the whole MDB2 instance by using the <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodsetfetchmode"> <function>setFetchMode</function></link> method. <example> <title>Determining fetch mode per call</title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $res =& $mdb2->query('SELECT * FROM users'); while ($row = $res->fetchRow(MDB2_FETCHMODE_ASSOC)) { echo $row['id'] . "\n"; } ?> ]]> </programlisting> </example> <example> <title>Changing default fetch mode</title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $mdb2->setFetchMode(MDB2_FETCHMODE_ASSOC); $res =& $mdb2->query('SELECT * FROM users'); while ($row = $res->fetchRow()) { echo $row['id'] . "\n"; } ?> ]]> </programlisting> </example> </para> </refsect2> <refsect2 id="package.database.mdb2.intro-fetch.desc.number"> <title>Fetch Rows by Number</title> <para> The PEAR MDB2 fetch system also supports an extra parameter to the fetch statement. So you can fetch rows from a result by number. This is especially helpful if you only want to show sets of an entire result (for example in building paginated HTML lists), fetch rows in an special order, etc. <example> <title>Fetching by number</title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... // the row to start fetching $from = 50; // how many results per page $resPage = 10; // the last row to fetch for this page $to = $from + $resPage; foreach (range($from, $to) as $rowNum) { if (!($row = $res->fetchRow(MDB2_FETCHMODE_ORDERED, $rowNum))) { break; } echo $row[0] . "\n"; } ?> ]]> </programlisting> </example> </para> </refsect2> <refsect2 id="package.database.mdb2.intro-fetch.desc.rows"> <title>Getting Entire Result Sets</title> <para> The MDB2_Driver_Common object provides several methods to read entire results sets: <link linkend="http://pear.php.net/package/MDB2/docs/latest/apidoc/MDB2/MDB2_Result_Common.html#methodfetchCol"> <function>fetchCol</function></link> and <link linkend="http://pear.php.net/package/MDB2/docs/latest/apidoc/MDB2/MDB2_Result_Common.html#methodfetchAll"> <function>fetchAll</function></link>. </para> </refsect2> <refsect2 id="package.database.mdb2.intro-fetch.desc.free"> <title>Freeing Result Sets</title> <para> Once you finish using a result set, if your script continues for a while, it's a good idea to save memory by freeing the result set via Use <link linkend="http://pear.php.net/package/MDB2/docs/latest/apidoc/MDB2/MDB2_Result_Common.html#methodfree"> <function>free</function></link>. <example> <title>Freeing</title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $res =& $mdb2->query('SELECT name, address FROM clients'); while ($row = $res->fetchRow()) { echo $row['name'] . ', ' . $row['address'] . "\n"; } $res->free(); ?> ]]> </programlisting> </example> </para> </refsect2> <refsect2 id="package.database.mdb2.intro-fetch.desc.more"> <title>Getting More Information From Query Results</title> <para> With MDB2 there are four ways to retrieve useful information about the query result sets themselves: </para> <example> <title> <link linkend="package.database.mdb2.db-result.numrows"> <function>numRows</function></link> tells how many rows are in a <command>SELECT</command> query result </title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $res =& $mdb2->query('SELECT * FROM phptest'); echo $res->numRows(); ?> ]]> </programlisting> </example> <example> <title> <link linkend="package.database.mdb2.db-result.numcols"> <function>numCols</function></link> tells how many columns are in a <command>SELECT</command> query result </title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $res =& $mdb2->query('SELECT * FROM phptest'); echo $res->numCols(); ?> ]]> </programlisting> </example> <example> <title> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodaffectedrows"> <function>rowCount</function></link> tells the internal which row number the internal result row pointer currently points to </title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $res =& $mdb2->query('SELECT * FROM phptest'); $res->fetchRow(); // returns 2 if the result set contains at least 2 rows echo $res->rowCount(); ?> ]]> </programlisting> </example> <example> <title> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodtableinfo"> <function>getColumnNames</function></link> returns an associative array with the names of the column of the result set as keys and the position inside the result set as the values <command>SELECT</command> query result </title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $res =& $mdb2->query('SELECT * FROM phptest'); print_r($res->getColumnNames($res)); ?> ]]> </programlisting> </example> </refsect2> <refsect2 id="package.database.mdb2.intro-fetch.desc.error"> <title>Checking for Errors</title> <para> Don't forget to use <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2.html#methodisError"> <function>isError</function></link> to check if your actions return a MDB2_Error object. </para> </refsect2> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-portability.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-portability.xml +++ peardoc/en/package/database/mdb2/intro-portability.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <!-- needs fixing for MDB2--> <refentry id="package.database.mdb2.intro-portability"> <refnamediv> <refname>Introduction - Portability</refname> <refpurpose>Database portability features</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-portability.desc"> &title.desc; <para> Each database management system (DBMS) has it's own behaviors. For example, some databases capitalize field names in their output, some lowercase them, while others leave them alone. These quirks make it difficult to port your scripts over to another server type. PEAR MDB2 strives to overcome these differences so your program can switch between DBMS's without any changes. </para> <para> You control which portability modes are enabled by using the <varname>portability</varname> configuration option. Configuration options are set via <link linkend="package.database.mdb2.db.connect"> <function>connect</function></link> and <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodsetoption"> <function>setOption</function></link>. </para> <para> The portability modes are bitwised, so they can be combined using <literal>|</literal> and removed using <literal>^</literal>. See the examples section below on how to do this. </para> </refsect1> <refsect1 id="package.database.mdb2.intro-portability.constants"> <title>Portability Mode Constants</title> <para> <itemizedlist> <listitem> <para> <constant>MDB2_PORTABILITY_ALL</constant> </para> <para> turn on all portability features </para> </listitem> <listitem> <para> <constant>MDB2_PORTABILITY_DELETE_COUNT</constant> </para> <para> force reporting the number of rows deleted. Some DBMS's don't count the number of rows deleted when performing simple <userinput>DELETE FROM tablename</userinput> queries. This mode tricks such DBMS's into telling the count by adding <userinput>WHERE 1=1</userinput> to the end of <command>DELETE</command> queries. </para> </listitem> <listitem> <para> <constant>MDB2_PORTABILITY_ERRORS</constant> </para> <para> makes certain error messages in certain drivers compatible with those from other DBMS's </para> <para> <table> <title>Error Code Re-mappings</title> <tgroup cols="4"> <thead> <row> <entry>Driver</entry> <entry>Description</entry> <entry>Old Constant</entry> <entry>New Constant</entry> </row> </thead> <tbody> <row> <entry> mysql, mysqli </entry> <entry> unique and primary key constraints </entry> <entry> <constant>MDB2_ERROR_ALREADY_EXISTS</constant> </entry> <entry> <constant>MDB2_ERROR_CONSTRAINT</constant> </entry> </row> <row> <entry> mysql, mysqli </entry> <entry> not-null constraints </entry> <entry> <constant>MDB2_ERROR_CONSTRAINT</constant> </entry> <entry> <constant>MDB2_ERROR_CONSTRAINT_NOT_NULL</constant> </entry> </row> <row> <entry> odbc(access) </entry> <entry> MS's ODBC driver mistakenly reports 'no such field' as code <computeroutput>07001</computeroutput>, which means 'too few parameters.' When this option is on, that code gets remapped. </entry> <entry> <constant>MDB2_ERROR_MISMATCH</constant> </entry> <entry> <constant>MDB2_ERROR_NOSUCHFIELD</constant> </entry> </row> </tbody> </tgroup> </table> </para> </listitem> <listitem> <para> <constant>MDB2_PORTABILITY_LOWERCASE</constant> </para> <para> convert names of tables and fields to lower case when using <function>get*</function>, <function>fetch*</function> and <function>tableInfo</function> </para> </listitem> <listitem> <para> <constant>MDB2_PORTABILITY_NONE</constant> (default) </para> <para> turn off all portability features </para> </listitem> <listitem> <para> <constant>MDB2_PORTABILITY_NULL_TO_EMPTY</constant> </para> <para> convert null values to empty strings in data output by <function>get*</function> and <function>fetch*</function>. Needed because Oracle considers empty strings to be null, while most other DBMS's know the difference between empty and null. </para> </listitem> <listitem> <para> <constant>MDB2_PORTABILITY_NUMROWS</constant> </para> <para> enable hack that makes <function>numRows</function> work in Oracle </para> </listitem> <listitem> <para> <constant>MDB2_PORTABILITY_RTRIM</constant> </para> <para> right trim the data output by <function>get*</function> and <function>fetch*</function> </para> </listitem> </itemizedlist> </para> </refsect1> <refsect1 id="package.database.mdb2.intro-portability.compatibility"> <title>Backwards Compatibility</title> <para> Some of this functionality used to be handled by the now deprecated <varname>optimize</varname> option. For backwards compatibility, when this option is set to <literal>portability</literal>, the following databases get these portability modes turned on: <itemizedlist> <listitem> <para> oci8: <constant>MDB2_PORTABILITY_LOWERCASE</constant> and <constant>MDB2_PORTABILITY_DELETE_COUNT</constant> </para> </listitem> <listitem> <para> fbsql, mysql, mysqli, sqlite: <constant>MDB2_PORTABILITY_DELETE_COUNT</constant> </para> </listitem> </itemizedlist> </para> <para> When the <varname>optimize</varname> option gets set to <literal>performance</literal> the portability mode is switched to <constant>MDB2_PORTABILITY_NONE</constant>. </para> </refsect1> <refsect1 id="package.database.mdb2.intro-portability.example"> &title.example; <example> <title>Turning on all portability options while connecting</title> <programlisting role="php"> <![CDATA[ <?php require_once 'MDB2.php'; $dsn = 'mysql://user:password@host/database' $options = array( 'debug' => 2, 'portability' => MDB2_PORTABILITY_ALL, ); $mdb2 =& MDB2::connect($dsn, $options); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } ?> ]]> </programlisting> </example> <example> <title> Using <function>setOption</function> to enable portability for lowercasing and trimming </title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $mdb2->setOption('portability', MDB2_PORTABILITY_LOWERCASE | MDB2_PORTABILITY_RTRIM); ?> ]]> </programlisting> </example> <example> <title> Using <function>setOption</function> to enable all portability options except trimming </title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $mdb2->setOption('portability', MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_RTRIM); ?> ]]> </programlisting> </example> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-query.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-query.xml +++ peardoc/en/package/database/mdb2/intro-query.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <!-- add information on the following methods: replace(), standaloneQuery(), subSelect() and setLimit() --> <refentry id="package.database.mdb2.intro-query"> <refnamediv> <refname>Introduction - Query</refname> <refpurpose>Performing queries</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-query.desc"> &title.desc; <para> PEAR MDB2 provides several methods for querying databases. The most direct method is <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodquery"> <function>query</function></link>. It takes a SQL query string as an argument. There are two possible returns: A new MDB2_Result object for queries that return results (such as <command>SELECT</command> queries), or a MDB2_Error object on failure. It should not be used with statements that manipulate data (such as <command>INSERT</command> queries) </para> <example> <title>Doing a query</title> <programlisting role="php"> <![CDATA[ <?php // Create a valid MDB2 object named $mdb2 // at the beginning of your program... require_once 'MDB2.php'; $mdb2 =& MDB2::connect('pgsql://usr:pw@localhost/dbnam'); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } // Proceed with a query... $res =& $mdb2->query('SELECT * FROM clients'); // Always check that result is not an error if (PEAR::isError($res)) { die($res->getMessage()); } ?> ]]> </programlisting> </example> <para> <function>exec</function> should be used for manipulation queries. There are two possible returns: An integer denoting the number of affected rows for statements that manipulate data (such as <command>INSERT</command> queries), or a MDB2_Error object on failure. It should not be used with statements that return results (such as <command>SELECT</command> queries) </para> <example> <title>Using exec to manipulate data</title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $sql = "INSERT INTO clients (name, address) VALUES ($name, §address)"; $data = 53; $affected =& $mdb2->exec($sql); // Always check that result is not an error if (PEAR::isError($res)) { die($affected->getMessage()); } ?> ]]> </programlisting> </example> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-sequences.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-sequences.xml +++ peardoc/en/package/database/mdb2/intro-sequences.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <!-- needs fixing for MDB2--> <refentry id="package.database.mdb2.intro-sequences"> <refnamediv> <refname>Introduction - Sequences</refname> <refpurpose>Sequences and auto-incrementing</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-sequences.desc"> &title.desc; <para> Sequences are a way of offering unique IDs for data rows. If you do most of your work with e.g. MySQL, think of sequences as another way of doing <command>AUTO_INCREMENT</command>. </para> <para> It's quite simple, first you request an ID, and then you insert that value in the ID field of the new row you're creating. You can have more than one sequence for all your tables, just be sure that you always use the same sequence for any particular table. To get the value of this unique ID use <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodnextid"> <function>nextId</function></link>, if a sequence doesn't exists, it will be created automatically. </para> <para> The sequence is automatically incremented each time <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodnextid"> <function>nextId</function></link> is called. </para> <para> <example> <title>Using a sequence</title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $id = $mdb2->nextId('mySequence'); if (PEAR::isError($id)) { die($id->getMessage()); } // Use the ID in your INSERT query $res =& $mdb2->query("INSERT INTO myTable (id, text) VALUES ($id, 'foo')"); ?> ]]> </programlisting> </example> </para> </refsect1> <refsect1 id="package.database.mdb2.intro-sequences.note"> &title.note; <warning> <para> When using PEAR MDB2's sequence methods, we strongly advise using these methods for all procedures, including the creation of the sequences. Do not use PEAR MDB2's methods to access sequences that were created directly in the DBMS. </para> <para> If you have a compelling reason to ignore this advice, be aware that the <parameter>$seq_name</parameter> argument given to all of PEAR MDB2's sequence methods are modified before MDB2 calls the underlying DBMS. </para> <para> <parameter>$seq_name</parameter> is passed through PHP's <function>sprintf</function> function using the value from the <varname>seqname_format</varname> option as <function>sprintf</function>'s format argument. The default <varname>seqname_format</varname> is <literal>%s_seq</literal>. So, for example, if you use <literal>person_id_sequence</literal> as the <parameter>$seq_name</parameter>, PEAR MDB2 will change that name to <literal>person_id_sequence_seq</literal> when querying the DBMS about creating/accessing/updating the sequence. </para> <para> The <varname>seqname_format</varname> can be modified when <link linkend="package.database.mdb2.db.connect"> <function>connect</function></link>'ing or via <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodsetoption"> <function>setOption</function></link>. </para> </warning> </refsect1> <refsect1 id="package.database.mdb2.intro-sequences.see"> &title.see; <para> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodcreatesequence"> <function>createSequence</function></link>, <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodnextid"> <function>nextId</function></link>, <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methoddropsequence"> <function>dropSequence</function></link> </para> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 -->
http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-auto.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-auto.xml +++ peardoc/en/package/database/mdb2/intro-auto.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <!-- needs fixing for MDB2--> <refentry id="package.database.mdb2.intro-auto"> <refnamediv> <refname>Introduction - autoPrepare & autoExecute</refname> <refpurpose>Automatically prepare and execute SQL statements</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-auto.desc"> &title.desc; <refsect2> <title>Purpose</title> <para> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoprepare"> <function>autoPrepare</function></link> and <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoexecute"> <function>autoExecute</function></link> reduce the need to write boring <command>INSERT</command> or <command>UPDATE</command> SQL queries which are difficult to maintain when you add a field for instance. </para> <para> Imagine you have a 'user' table with 3 fields (id, name and country). You have to write sql queries like: <programlisting role="sql"> <![CDATA[ INSERT INTO table (id, name, country) VALUES (?, ?, ?) UPDATE table SET id=?, name=?, country=? WHERE ... ]]> </programlisting> If you add a field ('birthYear' for example), you have to rewrite your queries which is boring and can lead to bugs (if you forget one query for instance). </para> </refsect2> <refsect2> <title>autoPrepare</title> <para> With <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoprepare"> <function>autoPrepare</function></link>, you don't have to write your insert or update queries. For example: <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $table_name = 'user'; $table_fields = array('id', 'name', 'country'); $sth = $mdb2->autoPrepare($table_name, $table_fields, MDB2_AUTOQUERY_INSERT); if (PEAR::isError($sth)) { die($sth->getMessage()); } ?> ]]> </programlisting> In this example, <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoprepare"> <function>autoPrepare</function></link> will build the following SQL query: <programlisting role="sql"> <![CDATA[ INSERT INTO user (id, name, country) VALUES (?, ?, ?) ]]> </programlisting> And then, it will call <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare"> <function>prepare</function></link> with it. </para> <para> To add records, you have to use <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodexecute"> <function>execute</function></link> or <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodexecutemultiple"> <function>executeMultiple</function></link> like: <programlisting role="php"> <![CDATA[ <?php // ... contining from the example above... $table_values = array(1, 'Fabien', 'France'); $res =& $mdb2->execute($sth, $table_values); if (PEAR::isError($res)) { die($res->getMessage()); } ?> ]]> </programlisting> So, you don't have to write any SQL <command>INSERT</command> queries! And it works with <command>UPDATE</command> queries too. For flexibility reasons, you have only to write the <command>WHERE</command> clause of the query. For instance: <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $table_name = 'user'; $table_fields = array('name', 'country'); $table_values = array('Bob', 'USA'); $sth = $mdb2->autoPrepare($table_name, $table_fields, MDB2_AUTOQUERY_UPDATE, 'id = 1'); if (PEAR::isError($sth)) { die($sth->getMessage()); } $res =& $mdb2->execute($sth, $table_values); if (PEAR::isError($res)) { die($res->getMessage()); } ?> ]]> </programlisting> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoprepare"> <function>autoPrepare</function></link> will build the following query: <programlisting role="sql"> <![CDATA[ UPDATE user SET name=?, country=? WHERE id=1 ]]> </programlisting> Then, it will call <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare"> <function>prepare</function></link> with it. </para> <para> Be careful, if you don't specify any <command>WHERE</command> clause, all the records of the table will be updated. </para> </refsect2> <refsect2> <title>autoExecute</title> <para> Using <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoexecute"> <function>autoExecute</function></link> is the easiest way to do insert or update queries. It is a mix of <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoprepare"> <function>autoPrepare</function></link> and <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodautoprepare"> <function>execute</function></link>. </para> <para> You only need an associative array (key => value) where keys are fields names and values are corresponding values of these fields. For instance: <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $table_name = 'user'; $fields_values = array( 'id' => 1, 'name' => 'Fabien', 'country' => 'France' ); $res = $mdb2->autoExecute($table_name, $fields_values, MDB2_AUTOQUERY_INSERT); if (PEAR::isError($res)) { die($res->getMessage()); } ?> ]]> </programlisting> And that's all! The following query is built and executed: <programlisting role="sql"> <![CDATA[ INSERT INTO user (id, name, country) VALUES (1, 'Fabien', 'France') ]]> </programlisting> </para> <para> And it's the same thing for <command>UPDATE</command> queries: <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $table_name = 'user'; $fields_values = array( 'name' => 'Fabien', 'country' => 'France' ); $res = $mdb2->autoExecute($table_name, $fields_values, MDB2_AUTOQUERY_UPDATE, 'id = 1'); if (PEAR::isError($res)) { die($res->getMessage()); } ?> ]]> </programlisting> which prepares and executes the following query: <programlisting role="sql"> <![CDATA[ UPDATE user SET name='Fabien', country='France' WHERE id = 1 ]]> </programlisting> </para> <para> Be careful, if you don't specify any <command>WHERE</command> statement, all the records of the table will be updated. </para> <warning> <para> The values passed in <parameter>$data</parameter> must be literals. Do not submit SQL functions (for example <literal>CURDATE()</literal>). SQL functions that should be performed at execution time need to be put in the prepared statement. </para> </warning> </refsect2> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-connect.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-connect.xml +++ peardoc/en/package/database/mdb2/intro-connect.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <!-- add information on the following methods: factory(), singleton() --> <refentry id="package.database.mdb2.intro-connect"> <refnamediv> <refname>Introduction - Connect</refname> <refpurpose>Connecting and disconnecting a database</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-connect.desc"> &title.desc; <para> To connect to a database you have to use the function <link linkend="package.database.mdb2.db.connect"> <function>connect</function></link>, which requires a valid <link linkend="package.database.mdb2.intro-dsn">DSN</link> as the first parameter. This parameter can either be a string or an array. If using an array, the array used gets merged with the default information: <programlisting role="configuration"> <![CDATA[ $dsn = array( 'phptype' => false, 'dbsyntax' => false, 'username' => false, 'password' => false, 'protocol' => false, 'hostspec' => false, 'port' => false, 'socket' => false, 'database' => false, 'new_ink' => false, ); ]]> </programlisting> Any elements you set override the defaults and the remainder stay at their defaults. </para> <simpara> The second parameter is the optional <parameter>$options</parameter> array that can contain runtime configuration settings for this package. See <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodsetOption"> <function>setOption</function></link> for more information on the available settings. </simpara> <simpara> In case of success you get a new instance of the database class. It is strongly recommened to check this return value with <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2.html#methodisError"> <function>isError</function></link>. </simpara> <simpara> To disconnect use the method <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methoddisconnect"> <function>disconnect</function></link> from your database class instance. </simpara> <example> <title>Connect and disconnect</title> <programlisting role="php"> <![CDATA[ <?php require_once 'MDB2.php'; $dsn = 'pgsql://someuser:apasswd@localhost/thedb'; $options = array( 'debug' => 2, 'result_buffering' => false, ); $mdb2 =& MDB2::connect($dsn, $options); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } // ... $mdb2->disconnect(); ?> ]]> </programlisting> </example> <example> <title>Connect using an array for the DSN information</title> <programlisting role="php"> <![CDATA[ <?php require_once 'MDB2.php'; $dsn = array( 'phptype' => 'pgsql', 'username' => 'someuser', 'password' => 'apasswd', 'hostspec' => 'localhost', 'database' => 'thedb', ); $options = array( 'debug' => 2, 'portability' => MDB2_PORTABILITY_ALL, ); $mdb2 =& MDB2::connect($dsn, $options); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } ?> ]]> </programlisting> <para> When connecting to SQLite using a DSN array, the value of the <varname>mode</varname> element must be a string: <programlisting role="php"> <![CDATA[ <?php $dsn = array( 'phptype' => 'sqlite', 'database' => 'thedb', 'mode' => '0644', ); ?> ]]> </programlisting> </para> </example> <example> <title> Connect to MySQLi via SSL using an array for the DSN information </title> <para> The <varname>ssl</varname> element of the <parameter>$options</parameter> array must be set to &true; in order for SSL to work. Each of the extra elements in the <parameter>$dsn</parameter> array (<varname>key</varname> through <varname>cipher</varname> in the example below) are optional. </para> <programlisting role="php"> <![CDATA[ <?php require_once 'MDB2.php'; $dsn = array( 'phptype' => 'mysqli', 'username' => 'someuser', 'password' => 'apasswd', 'hostspec' => 'localhost', 'database' => 'thedb', 'key' => 'client-key.pem', 'cert' => 'client-cert.pem', 'ca' => 'cacert.pem', 'capath' => '/path/to/ca/dir', 'cipher' => 'AES', ); $options = array( 'ssl' => true, ); $mdb2 =& MDB2::connect($dsn, $options); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } ?> ]]> </programlisting> </example> <example> <title>Connect to a PostgreSQL database via a socket</title> <programlisting role="php"> <![CDATA[ <?php require_once 'MDB2.php'; $dsn = 'pgsql://someuser:apasswd@unix(/tmp)/thedb'; $options = array( 'debug' => 2, 'portability' => MDB2_PORTABILITY_ALL, ); $mdb2 =& MDB2::connect($dsn, $options); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } ?> ]]> </programlisting> </example> </refsect1> <refsect1 id="package.database.mdb2.db-common.intro-connect.see"> &title.see; <para> <link linkend="package.database.mdb2.intro-portability"> <quote>Intro - Portability</quote></link> </para> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-dsn.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-dsn.xml +++ peardoc/en/package/database/mdb2/intro-dsn.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <refentry id="package.database.mdb2.intro-dsn"> <refnamediv> <refname>Introduction - DSN</refname> <refpurpose>The Data Source Name</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-dsn.desc"> &title.desc; <simpara> To connect to a database through PEAR::MDB2, you have to create a valid <acronym>DSN - data source name</acronym>. This DSN consists in the following parts: </simpara> <para> <simplelist> <member> <varname>phptype</varname>: Database backend used in PHP (i.e. <literal>mysql</literal> , <literal>pgsql</literal> etc.) </member> <member> <varname>dbsyntax</varname>: Database used with regards to SQL syntax etc. </member> <member> <varname>protocol</varname>: Communication protocol to use ( i.e. <literal>tcp</literal>, <literal>unix</literal> etc.) </member> <member> <varname>hostspec</varname>: Host specification (<literal>hostname[:port]</literal>) </member> <member> <varname>database</varname>: Database to use on the DBMS server </member> <member> <varname>username</varname>: User name for login </member> <member> <varname>password</varname>: Password for login </member> <member> <varname>proto_opts</varname>: Maybe used with <varname>protocol</varname> </member> <member> <varname>option</varname>: Additional connection options in URI query string format. options get separated by & </member> </simplelist> </para> <para> The DSN can either be provided as an associative array or as a string. The string format of the supplied DSN is in its fullest form: <programlisting role="url"> <![CDATA[ phptype(dbsyntax)://username:password@protocol+hostspec/database?option=value ]]> </programlisting> </para> <para> Most variations are allowed: <programlisting role="url"> <![CDATA[ phptype://username:password@protocol+hostspec:110//usr/db_file.db phptype://username:password@hostspec/database phptype://username:password@hostspec phptype://username@hostspec phptype://hostspec/database phptype://hostspec phptype:///database phptype:///database?option=value&anotheroption=anothervalue phptype(dbsyntax) phptype ]]> </programlisting> </para> <para> The currently supported database backends are: <programlisting role="configure"> <![CDATA[ fbsql -> FrontBase ibase -> InterBase (requires PHP 5) mssql -> Microsoft SQL Server (NOT for Sybase. Compile PHP --with-mssql) mysql -> MySQL (for MySQL <= 4.0) mysqli -> MySQL (for MySQL >= 4.1) (requires PHP 5) oci8 -> Oracle 7/8/9 pgsql -> PostgreSQL querysim -> QuerySim sqlite -> SQLite ]]> </programlisting> </para> <para> A second DSN format is supported <programlisting role="url"> <![CDATA[ phptype(syntax)://user:pass@protocol(proto_opts)/database ]]> </programlisting> </para> <para> If your <varname>database</varname>, <varname>option</varname> values, <varname>username</varname> or <varname>password</varname> contain characters used to delineate DSN parts, you can escape them via URI hex encodings: <programlisting role="url"> <![CDATA[ : = %3a / = %2f @ = %40 + = %2b ( = %28 ) = %29 ? = %3f = = %3d & = %26 ]]> </programlisting> </para> <warning> <para> Please note, that some features may be not supported by all database backends. </para> </warning> </refsect1> <refsect1 id="package.database.mdb2.intro-dsn.example"> &title.example; <example> <title>Connect to database through a socket</title> <programlisting role="url"> <![CDATA[ mysql://user@unix(/path/to/socket)/pear ]]> </programlisting> </example> <example> <title>Connect to database on a non standard port</title> <programlisting role="url"> <![CDATA[ pgsql://user:pass@tcp(localhost:5555)/pear ]]> </programlisting> </example> <example> <title>Connect to SQLite on a Unix machine using options</title> <programlisting role="url"> <![CDATA[ sqlite:////full/unix/path/to/file.db?mode=0666 ]]> </programlisting> </example> <example> <title>Connect to SQLite on a Windows machine using options</title> <programlisting role="url"> <![CDATA[ sqlite:///c:/full/windows/path/to/file.db?mode=0666 ]]> </programlisting> </example> <example> <title>Connect to MySQLi using SSL</title> <programlisting role="url"> <![CDATA[ mysqli://user:pass@localhost/pear?key=client-key.pem&cert=client-cert.pem ]]> </programlisting> </example> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-execute.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-execute.xml +++ peardoc/en/package/database/mdb2/intro-execute.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <!-- needs fixing for MDB2--> <refentry id="package.database.mdb2.intro-execute"> <refnamediv> <refname>Introduction - Prepare & Execute</refname> <refpurpose>Prepare and execute SQL statements</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-execute.desc"> &title.desc; <refsect2 id="package.database.mdb2.intro-execute.desc.purpose"> <title>Purpose</title> <para> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare"> <function>prepare</function></link> and <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodexecute"> <function>execute*</function></link> give you more power and flexibilty for query execution. Prepare/execute mode is helpful when you have to run the same query several times but with different values in it, such as adding a list of addresses into a database. </para> <para> Another place prepare/execute is useful is supporting databases which have different SQL syntaxes. Imagine you want to support two databases with different <command>INSERT</command> syntax: <programlisting> <![CDATA[ db1: INSERT INTO tbl_name (col1, col2) VALUES (expr1, expr2) db2: INSERT INTO tbl_name SET col1=expr1, col2=expr2 ]]> </programlisting> Correspondending to create multi-lingual scripts you can create a array with queries like this: <programlisting role="php"> <![CDATA[ $statement['db1']['INSERT_PERSON'] = 'INSERT INTO person (surname, name, age) VALUES (?, ?, ?)'; $statement['db2']['INSERT_PERSON'] = 'INSERT INTO person SET surname=?, name=?, age=?'; ]]> </programlisting> </para> </refsect2> <refsect2 id="package.database.mdb2.intro-execute.desc.prepare"> <title>Prepare</title> <para> To use the features above, you have to do two steps. Step one is to <emphasis>prepare</emphasis> the statement and the second is to <emphasis>execute</emphasis> it. </para> <para> To start out, you need to <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare"> <function>prepare</function></link> a generic SQL statment. Create a generic statment by writing the SQL query as usual: <programlisting role="sql"> <![CDATA[ SELECT surname, name, age FROM person WHERE name = 'name_to_find' AND age < age_limit ]]> </programlisting> Then substitute <quote>placeholders</quote> for the literal values which will be provided at run time: <programlisting role="sql"> <![CDATA[ SELECT surname, name, age FROM person WHERE name = ? AND age < ? ]]> </programlisting> Then pass this SQL statement to <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare"> <function>prepare</function></link>, which returns a statement handle to be used when calling <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodexecute"> <function>execute</function></link>. </para> <para> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare"> <function>prepare</function></link> can handle different types of placeholders (a.k.a. wildcards). <simplelist> <member> <literal>?</literal> - (recommended) stands for a scalar value like strings or numbers. The value will be automatically escaped and quoted according to the current DBMS's requirements. </member> <member> <literal>!</literal> - stands for a scalar value and will inserted into the statement <quote>as is</quote>. </member> <member> <literal>&</literal> - requires an existing filename, the content of this file will be included into the statment (i.e. for saving binary data of a graphic file in a database) </member> </simplelist> </para> <para> Use backslashes to escape placeholder characters if you don't want them to be interpreted as placeholders: <programlisting role="sql"> <![CDATA[ UPDATE foo SET col=? WHERE col='over \& under' ]]> </programlisting> </para> </refsect2> <refsect2 id="package.database.mdb2.intro-execute.desc.execute"> <title>Execute</title> <para> After preparing the statement, you can execute the query. This means to assign the variables to the prepared statement. To do this, <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodexecute"> <function>execute</function></link> requires two arguments: the statement handle returned by <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodprepare"> <function>prepare</function></link> and a scalar or array with the values to assign. </para> <para> <example> <title>Passing scalars to <function>execute</function></title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $sth = $mdb2->prepare('INSERT INTO numbers (number) VALUES (?)'); $mdb2->execute($sth, 1); $mdb2->execute($sth, 8); ?> ]]> </programlisting> </example> </para> <para> When a prepared statement has multiple placeholders, you must use an array to pass the values to <function>execute</function>. The first entry of the array represents the first placeholder, the second the second placeholder, etc. The order is independent of the type of placeholder used. </para> <para> <example> <title>Passing an array to <function>execute</function></title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $sth = $mdb2->prepare('INSERT INTO numbers VALUES (?, ?, ?)'); $data = array(1, 'one', 'en'); $mdb2->execute($sth, $data); ?> ]]> </programlisting> </example> </para> <warning> <para> The values passed in <parameter>$data</parameter> must be literals. Do not submit SQL functions (for example <literal>CURDATE()</literal>). SQL functions that should be performed at execution time need to be put in the prepared statement. Similarly, identifiers (i.e. table names and column names) can not be used because the names get validated during the prepare phase. </para> </warning> </refsect2> <refsect2 id="package.database.mdb2.intro-execute.desc.executemultiple"> <title>ExecuteMultiple</title> <para> MDB2 contains a process for executing several queries at once. So, rather than having to execute them manually, like this: <example> <title>Passing arrays to <function>execute</function></title> <programlisting role="php"> <![CDATA[ // Once you have a valid MDB2 object named $mdb2... $alldata = array(array(1, 'one', 'en'), array(2, 'two', 'to'), array(3, 'three', 'tre'), array(4, 'four', 'fire')); $sth = $mdb2->prepare('INSERT INTO numbers VALUES (?, ?, ?)'); foreach ($alldata as $row) { $mdb2->execute($sth, $row); } ]]> </programlisting> </example> which would issue four queries: <programlisting role="sql"> <![CDATA[ INSERT INTO numbers VALUES ('1', 'one', 'en') INSERT INTO numbers VALUES ('2', 'two', 'to') INSERT INTO numbers VALUES ('3', 'three', 'tre') INSERT INTO numbers VALUES ('4', 'four', 'fire') ]]> </programlisting> you can use <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodexecutemultiple"> <function>executeMultiple</function></link> to avoid the explicit foreach in the eample above: <example> <title> Using <function>executeMultiple</function> instead of <function>execute</function> </title> <programlisting role="php"> <![CDATA[ // Once you have a valid MDB2 object named $mdb2... $alldata = array(array(1, 'one', 'en'), array(2, 'two', 'to'), array(3, 'three', 'tre'), array(4, 'four', 'fire')); $sth = $mdb2->prepare('INSERT INTO numbers VALUES (?, ?, ?)'); $mdb2->executeMultiple($sth, $alldata); ]]> </programlisting> </example> </para> <para> The result is the same. If one of the records failed, the unfinished records will not be executed. </para> <para> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodexecute"> <function>execute*</function></link> has three possible returns: a new MDB2_Result_Common object for queries that return results (such as <command>SELECT</command> queries), &constant.db-ok; for queries that manipulate data (such as <command>INSERT</command> queries) or a MDB2_Error object on failure </para> </refsect2> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-fetch.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-fetch.xml +++ peardoc/en/package/database/mdb2/intro-fetch.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <!-- add information on the following methods: seek(), getResource(), bindColumn(), setResultTypes() and nextResult() --> <refentry id="package.database.mdb2.intro-fetch"> <refnamediv> <refname>Introduction - Results</refname> <refpurpose>Obtaining data from query results</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-fetch.desc"> &title.desc; <refsect2 id="package.database.mdb2.intro-fetch.desc.fetch"> <title>Fetching Individual Rows From Query Results</title> <para> The MDB2_Result_Common object provides two methods for fetching data from rows of a result set: <link linkend="http://pear.php.net/package/MDB2/docs/latest/apidoc/MDB2/MDB2_Result_Common.html#methodfetchOne"> <function>fetchOne</function></link>, <link linkend="http://pear.php.net/package/MDB2/docs/latest/apidoc/MDB2/MDB2_Result_Common.html#methodfetchRow"> <function>fetchRow</function></link>, <link linkend="http://pear.php.net/package/MDB2/docs/latest/apidoc/MDB2/MDB2_Result_Common.html#methodfetchCol"> <function>fetchCol</function></link> and <link linkend="http://pear.php.net/package/MDB2/docs/latest/apidoc/MDB2/MDB2_Result_Common.html#methodfetchAll"> <function>fetchAll</function></link>. </para> <para> <function>fetchRow</function> and <function>fetchOne</function> read an entire row or a single column respectively. The result pointer gets moved to the next row each time these methods are called. &null; is returned when the end of the result set is reached. </para> <para> <function>fetchRow</function> reads an entire row as an array and <function>fetchOne</function> reads an single column into a scalar. The result pointer gets moved to the next row each time these methods are called. &null; is returned when the end of the result set is reached. </para> <para> MDB2_Error is returned if an error is encountered. </para> <example> <title>Fetching a result set</title> <programlisting role="php"> <![CDATA[ <?php // Create a valid MDB2 object named $mdb2 // at the beginning of your program... require_once 'MDB2.php'; $mdb2 =& MDB2::connect('pgsql://usr:pw@localhost/dbnam'); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } // Proceed with getting some data... $res =& $mdb2->query('SELECT * FROM mytable'); // Get each row of data on each iteration until // there are no more rows while (($row = $res->fetchRow())) { // Assuming MDB2's default fetchmode is MDB2_FETCHMODE_ORDERED echo $row[0] . "\n"; } // while (($one = $res->fetchOne())) { // echo $one . "\n"; // } ?> ]]> </programlisting> </example> </refsect2> <refsect2 id="package.database.mdb2.intro-fetch.desc.format"> <title>Formats of Fetched Rows</title> <para> The data from the row of a query result can be placed into one of three constructs: an ordered array (with column numbers as keys), an associative array (with column names as keys) or an object (with column names as properties). </para> <para> <constant>MDB2_FETCHMODE_ORDERED</constant> (default) <screen> <![CDATA[ Array ( [0] => 28 [1] => hi ) ]]> </screen> </para> <para> <constant>MDB2_FETCHMODE_ASSOC</constant> <screen> <![CDATA[ Array ( [a] => 28 [b] => hi ) ]]> </screen> </para> <para> <constant>MDB2_FETCHMODE_OBJECT</constant> <screen> <![CDATA[ stdClass Object ( [a] => 28 [b] => hi ) ]]> </screen> </para> <para> NOTE: When a query contains the same column name more than once (such as when joining tables which have duplicate column names) and the fetch mode is <constant>MDB2_FETCHMODE_ASSOC</constant> or <constant>MDB2_FETCHMODE_OBJECT</constant>, the data from the last column with a given name will be the one returned. There are two immediate options to work around this issue: <simplelist> <member> Use aliases in your query, for example <userinput>People.Name AS PersonName</userinput> </member> <member> Change the fetch mode to <constant>MDB2_FETCHMODE_ORDERED</constant> </member> </simplelist> </para> <para> TIP: If you are running into this issue, it likely indicates poor planning of the database schema. Either data is needlessly being duplicated or the same names are being used for different kinds of data. </para> </refsect2> <refsect2 id="package.database.mdb2.intro-fetch.desc.set"> <title>How to Set Formats</title> <para> You can set the fetch mode each time you call a fetch method and/or you can set the default fetch mode for the whole MDB2 instance by using the <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodsetfetchmode"> <function>setFetchMode</function></link> method. <example> <title>Determining fetch mode per call</title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $res =& $mdb2->query('SELECT * FROM users'); while ($row = $res->fetchRow(MDB2_FETCHMODE_ASSOC)) { echo $row['id'] . "\n"; } ?> ]]> </programlisting> </example> <example> <title>Changing default fetch mode</title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $mdb2->setFetchMode(MDB2_FETCHMODE_ASSOC); $res =& $mdb2->query('SELECT * FROM users'); while ($row = $res->fetchRow()) { echo $row['id'] . "\n"; } ?> ]]> </programlisting> </example> </para> </refsect2> <refsect2 id="package.database.mdb2.intro-fetch.desc.number"> <title>Fetch Rows by Number</title> <para> The PEAR MDB2 fetch system also supports an extra parameter to the fetch statement. So you can fetch rows from a result by number. This is especially helpful if you only want to show sets of an entire result (for example in building paginated HTML lists), fetch rows in an special order, etc. <example> <title>Fetching by number</title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... // the row to start fetching $from = 50; // how many results per page $resPage = 10; // the last row to fetch for this page $to = $from + $resPage; foreach (range($from, $to) as $rowNum) { if (!($row = $res->fetchRow(MDB2_FETCHMODE_ORDERED, $rowNum))) { break; } echo $row[0] . "\n"; } ?> ]]> </programlisting> </example> </para> </refsect2> <refsect2 id="package.database.mdb2.intro-fetch.desc.rows"> <title>Getting Entire Result Sets</title> <para> The MDB2_Driver_Common object provides several methods to read entire results sets: <link linkend="http://pear.php.net/package/MDB2/docs/latest/apidoc/MDB2/MDB2_Result_Common.html#methodfetchCol"> <function>fetchCol</function></link> and <link linkend="http://pear.php.net/package/MDB2/docs/latest/apidoc/MDB2/MDB2_Result_Common.html#methodfetchAll"> <function>fetchAll</function></link>. </para> </refsect2> <refsect2 id="package.database.mdb2.intro-fetch.desc.free"> <title>Freeing Result Sets</title> <para> Once you finish using a result set, if your script continues for a while, it's a good idea to save memory by freeing the result set via Use <link linkend="http://pear.php.net/package/MDB2/docs/latest/apidoc/MDB2/MDB2_Result_Common.html#methodfree"> <function>free</function></link>. <example> <title>Freeing</title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $res =& $mdb2->query('SELECT name, address FROM clients'); while ($row = $res->fetchRow()) { echo $row['name'] . ', ' . $row['address'] . "\n"; } $res->free(); ?> ]]> </programlisting> </example> </para> </refsect2> <refsect2 id="package.database.mdb2.intro-fetch.desc.more"> <title>Getting More Information From Query Results</title> <para> With MDB2 there are four ways to retrieve useful information about the query result sets themselves: </para> <example> <title> <link linkend="package.database.mdb2.db-result.numrows"> <function>numRows</function></link> tells how many rows are in a <command>SELECT</command> query result </title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $res =& $mdb2->query('SELECT * FROM phptest'); echo $res->numRows(); ?> ]]> </programlisting> </example> <example> <title> <link linkend="package.database.mdb2.db-result.numcols"> <function>numCols</function></link> tells how many columns are in a <command>SELECT</command> query result </title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $res =& $mdb2->query('SELECT * FROM phptest'); echo $res->numCols(); ?> ]]> </programlisting> </example> <example> <title> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodaffectedrows"> <function>rowCount</function></link> tells the internal which row number the internal result row pointer currently points to </title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $res =& $mdb2->query('SELECT * FROM phptest'); $res->fetchRow(); // returns 2 if the result set contains at least 2 rows echo $res->rowCount(); ?> ]]> </programlisting> </example> <example> <title> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodtableinfo"> <function>getColumnNames</function></link> returns an associative array with the names of the column of the result set as keys and the position inside the result set as the values <command>SELECT</command> query result </title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $res =& $mdb2->query('SELECT * FROM phptest'); print_r($res->getColumnNames($res)); ?> ]]> </programlisting> </example> </refsect2> <refsect2 id="package.database.mdb2.intro-fetch.desc.error"> <title>Checking for Errors</title> <para> Don't forget to use <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2.html#methodisError"> <function>isError</function></link> to check if your actions return a MDB2_Error object. </para> </refsect2> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-portability.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-portability.xml +++ peardoc/en/package/database/mdb2/intro-portability.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <!-- needs fixing for MDB2--> <refentry id="package.database.mdb2.intro-portability"> <refnamediv> <refname>Introduction - Portability</refname> <refpurpose>Database portability features</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-portability.desc"> &title.desc; <para> Each database management system (DBMS) has it's own behaviors. For example, some databases capitalize field names in their output, some lowercase them, while others leave them alone. These quirks make it difficult to port your scripts over to another server type. PEAR MDB2 strives to overcome these differences so your program can switch between DBMS's without any changes. </para> <para> You control which portability modes are enabled by using the <varname>portability</varname> configuration option. Configuration options are set via <link linkend="package.database.mdb2.db.connect"> <function>connect</function></link> and <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodsetoption"> <function>setOption</function></link>. </para> <para> The portability modes are bitwised, so they can be combined using <literal>|</literal> and removed using <literal>^</literal>. See the examples section below on how to do this. </para> </refsect1> <refsect1 id="package.database.mdb2.intro-portability.constants"> <title>Portability Mode Constants</title> <para> <itemizedlist> <listitem> <para> <constant>MDB2_PORTABILITY_ALL</constant> </para> <para> turn on all portability features </para> </listitem> <listitem> <para> <constant>MDB2_PORTABILITY_DELETE_COUNT</constant> </para> <para> force reporting the number of rows deleted. Some DBMS's don't count the number of rows deleted when performing simple <userinput>DELETE FROM tablename</userinput> queries. This mode tricks such DBMS's into telling the count by adding <userinput>WHERE 1=1</userinput> to the end of <command>DELETE</command> queries. </para> </listitem> <listitem> <para> <constant>MDB2_PORTABILITY_ERRORS</constant> </para> <para> makes certain error messages in certain drivers compatible with those from other DBMS's </para> <para> <table> <title>Error Code Re-mappings</title> <tgroup cols="4"> <thead> <row> <entry>Driver</entry> <entry>Description</entry> <entry>Old Constant</entry> <entry>New Constant</entry> </row> </thead> <tbody> <row> <entry> mysql, mysqli </entry> <entry> unique and primary key constraints </entry> <entry> <constant>MDB2_ERROR_ALREADY_EXISTS</constant> </entry> <entry> <constant>MDB2_ERROR_CONSTRAINT</constant> </entry> </row> <row> <entry> mysql, mysqli </entry> <entry> not-null constraints </entry> <entry> <constant>MDB2_ERROR_CONSTRAINT</constant> </entry> <entry> <constant>MDB2_ERROR_CONSTRAINT_NOT_NULL</constant> </entry> </row> <row> <entry> odbc(access) </entry> <entry> MS's ODBC driver mistakenly reports 'no such field' as code <computeroutput>07001</computeroutput>, which means 'too few parameters.' When this option is on, that code gets remapped. </entry> <entry> <constant>MDB2_ERROR_MISMATCH</constant> </entry> <entry> <constant>MDB2_ERROR_NOSUCHFIELD</constant> </entry> </row> </tbody> </tgroup> </table> </para> </listitem> <listitem> <para> <constant>MDB2_PORTABILITY_LOWERCASE</constant> </para> <para> convert names of tables and fields to lower case when using <function>get*</function>, <function>fetch*</function> and <function>tableInfo</function> </para> </listitem> <listitem> <para> <constant>MDB2_PORTABILITY_NONE</constant> (default) </para> <para> turn off all portability features </para> </listitem> <listitem> <para> <constant>MDB2_PORTABILITY_NULL_TO_EMPTY</constant> </para> <para> convert null values to empty strings in data output by <function>get*</function> and <function>fetch*</function>. Needed because Oracle considers empty strings to be null, while most other DBMS's know the difference between empty and null. </para> </listitem> <listitem> <para> <constant>MDB2_PORTABILITY_NUMROWS</constant> </para> <para> enable hack that makes <function>numRows</function> work in Oracle </para> </listitem> <listitem> <para> <constant>MDB2_PORTABILITY_RTRIM</constant> </para> <para> right trim the data output by <function>get*</function> and <function>fetch*</function> </para> </listitem> </itemizedlist> </para> </refsect1> <refsect1 id="package.database.mdb2.intro-portability.compatibility"> <title>Backwards Compatibility</title> <para> Some of this functionality used to be handled by the now deprecated <varname>optimize</varname> option. For backwards compatibility, when this option is set to <literal>portability</literal>, the following databases get these portability modes turned on: <itemizedlist> <listitem> <para> oci8: <constant>MDB2_PORTABILITY_LOWERCASE</constant> and <constant>MDB2_PORTABILITY_DELETE_COUNT</constant> </para> </listitem> <listitem> <para> fbsql, mysql, mysqli, sqlite: <constant>MDB2_PORTABILITY_DELETE_COUNT</constant> </para> </listitem> </itemizedlist> </para> <para> When the <varname>optimize</varname> option gets set to <literal>performance</literal> the portability mode is switched to <constant>MDB2_PORTABILITY_NONE</constant>. </para> </refsect1> <refsect1 id="package.database.mdb2.intro-portability.example"> &title.example; <example> <title>Turning on all portability options while connecting</title> <programlisting role="php"> <![CDATA[ <?php require_once 'MDB2.php'; $dsn = 'mysql://user:password@host/database' $options = array( 'debug' => 2, 'portability' => MDB2_PORTABILITY_ALL, ); $mdb2 =& MDB2::connect($dsn, $options); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } ?> ]]> </programlisting> </example> <example> <title> Using <function>setOption</function> to enable portability for lowercasing and trimming </title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $mdb2->setOption('portability', MDB2_PORTABILITY_LOWERCASE | MDB2_PORTABILITY_RTRIM); ?> ]]> </programlisting> </example> <example> <title> Using <function>setOption</function> to enable all portability options except trimming </title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $mdb2->setOption('portability', MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_RTRIM); ?> ]]> </programlisting> </example> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-query.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-query.xml +++ peardoc/en/package/database/mdb2/intro-query.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <!-- add information on the following methods: replace(), standaloneQuery(), subSelect() and setLimit() --> <refentry id="package.database.mdb2.intro-query"> <refnamediv> <refname>Introduction - Query</refname> <refpurpose>Performing queries</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-query.desc"> &title.desc; <para> PEAR MDB2 provides several methods for querying databases. The most direct method is <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodquery"> <function>query</function></link>. It takes a SQL query string as an argument. There are two possible returns: A new MDB2_Result object for queries that return results (such as <command>SELECT</command> queries), or a MDB2_Error object on failure. It should not be used with statements that manipulate data (such as <command>INSERT</command> queries) </para> <example> <title>Doing a query</title> <programlisting role="php"> <![CDATA[ <?php // Create a valid MDB2 object named $mdb2 // at the beginning of your program... require_once 'MDB2.php'; $mdb2 =& MDB2::connect('pgsql://usr:pw@localhost/dbnam'); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } // Proceed with a query... $res =& $mdb2->query('SELECT * FROM clients'); // Always check that result is not an error if (PEAR::isError($res)) { die($res->getMessage()); } ?> ]]> </programlisting> </example> <para> <function>exec</function> should be used for manipulation queries. There are two possible returns: An integer denoting the number of affected rows for statements that manipulate data (such as <command>INSERT</command> queries), or a MDB2_Error object on failure. It should not be used with statements that return results (such as <command>SELECT</command> queries) </para> <example> <title>Using exec to manipulate data</title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $sql = "INSERT INTO clients (name, address) VALUES ($name, §address)"; $data = 53; $affected =& $mdb2->exec($sql); // Always check that result is not an error if (PEAR::isError($res)) { die($affected->getMessage()); } ?> ]]> </programlisting> </example> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 --> http://cvs.php.net/viewcvs.cgi/peardoc/en/package/database/mdb2/intro-sequences.xml?view=markup&rev=1.1 Index: peardoc/en/package/database/mdb2/intro-sequences.xml +++ peardoc/en/package/database/mdb2/intro-sequences.xml <?xml version="1.0" encoding="iso-8859-1" ?> <!-- $Revision: 1.1 $ --> <!-- needs fixing for MDB2--> <refentry id="package.database.mdb2.intro-sequences"> <refnamediv> <refname>Introduction - Sequences</refname> <refpurpose>Sequences and auto-incrementing</refpurpose> </refnamediv> <refsect1 id="package.database.mdb2.intro-sequences.desc"> &title.desc; <para> Sequences are a way of offering unique IDs for data rows. If you do most of your work with e.g. MySQL, think of sequences as another way of doing <command>AUTO_INCREMENT</command>. </para> <para> It's quite simple, first you request an ID, and then you insert that value in the ID field of the new row you're creating. You can have more than one sequence for all your tables, just be sure that you always use the same sequence for any particular table. To get the value of this unique ID use <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodnextid"> <function>nextId</function></link>, if a sequence doesn't exists, it will be created automatically. </para> <para> The sequence is automatically incremented each time <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodnextid"> <function>nextId</function></link> is called. </para> <para> <example> <title>Using a sequence</title> <programlisting role="php"> <![CDATA[ <?php // Once you have a valid MDB2 object named $mdb2... $id = $mdb2->nextId('mySequence'); if (PEAR::isError($id)) { die($id->getMessage()); } // Use the ID in your INSERT query $res =& $mdb2->query("INSERT INTO myTable (id, text) VALUES ($id, 'foo')"); ?> ]]> </programlisting> </example> </para> </refsect1> <refsect1 id="package.database.mdb2.intro-sequences.note"> &title.note; <warning> <para> When using PEAR MDB2's sequence methods, we strongly advise using these methods for all procedures, including the creation of the sequences. Do not use PEAR MDB2's methods to access sequences that were created directly in the DBMS. </para> <para> If you have a compelling reason to ignore this advice, be aware that the <parameter>$seq_name</parameter> argument given to all of PEAR MDB2's sequence methods are modified before MDB2 calls the underlying DBMS. </para> <para> <parameter>$seq_name</parameter> is passed through PHP's <function>sprintf</function> function using the value from the <varname>seqname_format</varname> option as <function>sprintf</function>'s format argument. The default <varname>seqname_format</varname> is <literal>%s_seq</literal>. So, for example, if you use <literal>person_id_sequence</literal> as the <parameter>$seq_name</parameter>, PEAR MDB2 will change that name to <literal>person_id_sequence_seq</literal> when querying the DBMS about creating/accessing/updating the sequence. </para> <para> The <varname>seqname_format</varname> can be modified when <link linkend="package.database.mdb2.db.connect"> <function>connect</function></link>'ing or via <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodsetoption"> <function>setOption</function></link>. </para> </warning> </refsect1> <refsect1 id="package.database.mdb2.intro-sequences.see"> &title.see; <para> <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodcreatesequence"> <function>createSequence</function></link>, <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methodnextid"> <function>nextId</function></link>, <link linkend="http://pear.php.net/package/MDB2/docs/latest/MDB2/MDB2_Driver_Common.html#methoddropsequence"> <function>dropSequence</function></link> </para> </refsect1> </refentry> <!-- Keep this comment at the end of the file Local variables: mode: sgml sgml-omittag:t sgml-shorttag:t sgml-minimize-attributes:nil sgml-always-quote-attributes:t sgml-indent-step:1 sgml-indent-data:t sgml-parent-document:nil sgml-default-dtd-file:"../../../../manual.ced" sgml-exposed-tags:nil sgml-local-catalogs:nil sgml-local-ecat-files:nil End: vim600: syn=xml fen fdm=syntax fdl=2 si vim: et tw=78 syn=sgml vi: ts=1 sw=1 -->