PHP 8.3.4 Released!

Funciones de IBM DB2

Tabla de contenidos

  • db2_autocommit — Devuelve o establece el estado de AUTOCOMMIT en una conexión de bases de datos
  • db2_bind_param — Vincula una variable PHP a un parámetro de una sentencia SQL
  • db2_client_info — Devuelve un objeto cuyas propiedades describen cliente de una base de datos DB2
  • db2_close — Cierra una conexión a base de datos
  • db2_column_privileges — Obtiene la lista de columnas y permisos asociados a una tabla
  • db2_columns — Devuelve los campos de una tabla y sus metadatos asociados.
  • db2_commit — Confirmar una transacción
  • db2_conn_error — Devolver una cadena que contenga el valor SQLSTATE devuelto por el último intento de conexión.
  • db2_conn_errormsg — Devolver el último mensaje de error de la conexión y su valor SQLCODE
  • db2_connect — Devolver una conexión a la base de datos
  • db2_cursor_type — Determinar el tipo de cursor utilizado en una consulta
  • db2_escape_string — Escapar ciertos caracteres especiales
  • db2_exec — Ejecutar directamente una sentencia SQL
  • db2_execute — Ejecutar una sentencia SQL preparada
  • db2_fetch_array — Devolver un arreglo, indexado por la posición de las columnas, que represanta una fila de un bloque de resultados
  • db2_fetch_assoc — Devolver un arreglo, indexado por el nombre de las columnas, representando una fila del bloque de resultados
  • db2_fetch_both — Devolver un arreglo, indexado por el nombre y por la posición de la columna, representando una fila de un bloque de resultados
  • db2_fetch_object — Devolver un objeto con atributos que representan a las columnas de una fila extraida
  • db2_fetch_row — Establecer el apuntador de los resultados hacia la siguiente fila o a la fila solicitada
  • db2_field_display_size — Devolver el número máximo de bytes requeridos para mostrar una columna
  • db2_field_name — Devolver el nombre de la columna indicada del resultado
  • db2_field_num — Devolver la posición de la columna indicada en un resultado
  • db2_field_precision — Devolver la precisión de la columna indicada en el resultado
  • db2_field_scale — Devolver la escala de la columna indicada en el resultado
  • db2_field_type — Devolver el tipo de dato de la columna indicada en un resultado
  • db2_field_width — Devolver el tamaño del valor contenido en la columna indicada
  • db2_foreign_keys — Devolver un resultado que contenga las llaves foraneas de una tabla
  • db2_free_result — Liberar los recursos asociados con un resultado
  • db2_free_stmt — Liberar un recurso indicado
  • db2_get_option — Devolver el valor de la opción correpondiente a una conexión o sentencia
  • db2_last_insert_id — Devolver el ID autogenerado el la última sentencia INSERT ejecutada correctamente en la conexión
  • db2_lob_read — Obtener un segmento, de tamaño definido por el usuario, de un archivo LOB
  • db2_next_result — Solicitar el siguiente resultado de un procedimiento almacendo
  • db2_num_fields — Devolver el número de campos que contiene un resultado
  • db2_num_rows — Devolver el número de filas afectadas por una sentencia SQL
  • db2_pclose — Cerrar una conexión persistente a la base de datos
  • db2_pconnect — Devolver una conexión persistente a la base de datos
  • db2_prepare — Prepara un comando SQL para su ejecución
  • db2_primary_keys — Devolver un resultado con las llaves primarias de una tabla
  • db2_procedure_columns — Devolver un resultado con los parámetros de los procedimientos almacenados
  • db2_procedures — Devolver un resultado con los procedimientos almacenados registrados en la base de datos
  • db2_result — Devolver una columna específica del resultado
  • db2_rollback — Cancelar una transacción
  • db2_server_info — Returns an object with properties that describe the DB2 database server
  • db2_set_option — Set options for connection or statement resources
  • db2_special_columns — Returns a result set listing the unique row identifier columns for a table
  • db2_statistics — Returns a result set listing the index and statistics for a table
  • db2_stmt_error — Returns a string containing the SQLSTATE returned by an SQL statement
  • db2_stmt_errormsg — Returns a string containing the last SQL statement error message
  • db2_table_privileges — Returns a result set listing the tables and associated privileges in a database
  • db2_tables — Returns a result set listing the tables and associated metadata in a database
add a note

User Contributed Notes 5 notes

up
3
igtoth at gmail dot com
9 years ago
// IBM DB2 funcitons like MySQL (ODBC based)
// "Ighor Toth" <igtoth@gmail.com>
// Date: 08/05/2014

// usage:
// db2_connect(verbose,instance,username,password); -> also reads config file if nothing declared db2.conf.inc.php
// db2_query(db2_connect_return,sql)
// db2_fetch_array(result);
// db2_fetch_object(result);
// db2_display_table(db2_connect_return,sql); // select only

function db2_connect($verbose = null,$db2name = null,$username = null,$password = null) {
if(!isset($verbose)){
$verbose = TRUE; // TRUE or FALSE, if not set TRUE
}
if(!isset($db2name)){ // NOT DECLARED
include("db2.conf.inc.php"); // CHECK CONFIG FILE
if(!isset($db2name)){
if ($verbose == TRUE){
echo ("DB2 Instance not selected");
exit();
} else {
exit();
}
}
} else if (!isset($username)){
echo ("DB2 Instance username not specified");
exit();
}
$db2conn = odbc_connect($db2name, $username, $password);
if (($verbose == TRUE) && ($db2conn == 0)) {
echo("Connection to database failed.");
$sqlerror = odbc_errormsg($db2conn);
echo($sqlerror);
}
return($db2conn);
}

function db2_query($db2conn,$sql){
$result = odbc_exec($db2conn, $sql);
if ($result == 0) {
echo("QUERY = '$sql' FAILED.<br>\n");
$sqlerror = odbc_errormsg($db2conn);
echo($sqlerror);
} else {
// odbc_result_all prints all of the rows
// for a result set ID as an HTML table
return $result;
}
}

function db2_fetch_array($result, $rownumber=null){
$array = array();
if (!($cols = odbc_fetch_into($result, $result_array, $rownumber))) {
return false;
}
for ($i = 1; $i <= $cols; $i++) {
$array[odbc_field_name($result, $i)] = $result_array[$i - 1];
}
return $array;
}

function db2_fetch_object($result){
if(function_exists("db2_fetch_object")) return db2_fetch_object($result);
$rs = array();
$rs_obj = false;
if( odbc_fetch_into($result, $rs) ){
foreach( $rs as $key=>$value ){
$fkey = odbc_field_name($result, $key+1);
$rs_obj->$fkey = trim($value);
}
}
return $rs_obj;
}

function db2_display_table($db2conn,$sql) {
// select all rows from the table
if(!isset($db2conn)||!isset($sql)){
echo("ERROR db2_display_table: Function missing arguments");
exit();
}
$check = explode(" ",$sql);
if($check[0]!="SELECT"){
echo("ERROR db2_display_table: Not SELECT SQL query");
}
if ($db2conn != 0) {
// odbc_exec returns 0 if the statement fails;
// otherwise it returns a result set ID
$result = odbc_exec($db2conn, $sql);
if ($result == 0) {
echo("SELECT statement failed.");
$sqlerror = odbc_errormsg($db2conn);
echo($sqlerror);
} else {
// odbc_result_all prints all of the rows
// for a result set ID as an HTML table
odbc_result_all($result);
}
}
}
up
1
Richard dot Ablewhite at gmail dot com
15 years ago
There seems to be a lot of good documentation
for Linux users compiling PHP with DB2 support,
but decent Windows notes are minimal.

You do not need to install full DB2 clients to get DB2
working with DB2, all you need is the IBM Data
Server Driver for ODBC, CLI, and .NET which is only
16.1 meg.

You can download the driver from here:

Direct Link:
ftp://ftp.software.ibm.com/ps/products/db2/fixes2/englsh-us/
db2_v95/dsdriver/fp2/v9.5fp2_nt32_dsdriver_EN.exe

Home Page:
http://www-01.ibm.com/support/docview.wss?rs=71&uid=swg21287889

This includes both the drivers required and the PHP
dll php_ibm_db2_5.2.2.dll

Once installed the drivers do not setup the correct
path environmental variable,
so add the following to your path:

C:\Program Files\IBM\IBM DATA SERVER DRIVER\bin

Once thats done all should work! No massive
400meg client downloads required.

Whats even better about these drivers is that you
dont need to install them,
you can simply copy the bin directory to any server,
add it to your path and it will just work.
This is great for anyone developing PHP-GTK applications,
I copy the bin directory into my php-gkt2 directory
and execute using the following batch script:

path = %PATH%;.\IBM DATA SERVER DRIVER\bin
php-win.exe %*

This lets me role out lightweight DB2 client desktop
apps that dont have to be installed,
can just be coppied from PC to PC or ran over a
network or from USB stick.

As your only installing the client drivers you wont be
able to catalog databases,
so always use the full connection string. Here is a
quick bit of code to get you started:

$database = 'databasename';
$user = 'user';
$password = 'password';
$hostname = '127.0.0.1';
$port = 50000;

$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
"HOSTNAME=$hostname;PORT=$port;".
"PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');

$query = 'SELECT * FROM TABLE';
$res = db2_prepare($conn, $query);
db2_execute($res);

while ($row = db2_fetch_array($res)) {
print_r($row);
}
up
1
brent dot halsey at gmail dot com
15 years ago
Spent a lot of time trying to get this to work on a 64bit box. You'll need to make sure you set your db2 client to 64 bit mode! If you didn't set your instance to 64bit, you can run ./db2iupdt -w64 db2instance as root to set it. Hope this helps someone!
up
0
Exi
15 years ago
The DB/2 Run-Time-Client can be found here:
http://www-1.ibm.com/support/docview.wss?rs=71&uid=swg21255394
Select the 'Runtime Client Installable for Windows' further down the page and download it.
Clients for other platform (incl. 64-Bit Windows) are also available from that page.
up
-1
kfoubert at sitecrafting dot com
15 years ago
If you wish to connect to an iSeries Server, such as an AS/400, there are two options. Installing DB2 Express-C v9.5 and purchasing DB2 Connect Personal Edition for about $500 or getting System I Access for Linux, which is a free download. Please note the server requirements for each of these. For example, we originally went with DB2 Express-C and decided upon Ubuntu 7.10, but learned about System I Access, from an IBM rep, which requires redhat package manager, after the entire server was up and running.

DB2 Express-C
http://www-306.ibm.com/software/data/db2/express/

DB2 Connect Personal
http://www-306.ibm.com/software/data/db2/db2connect/edition-pe.html

System I Access for Linux
http://www-03.ibm.com/systems/i/software/access/index.html
NOTE: System I Access requires redhat package manager.
To Top