1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2016 The PHP Group                                |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | http://www.php.net/license/3_01.txt                                  |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Stig S�ther Bakken <ssb@php.net>                            |
16   |          Andreas Karajannis <Andreas.Karajannis@gmd.de>              |
17   |          Frank M. Kromann <frank@kromann.info>  Support for DB/2 CLI |
18   |          Kevin N. Shallow <kshallow@tampabay.rr.com> Birdstep Support|
19   |          Daniel R. Kalowsky <kalowsky@php.net>                       |
20   +----------------------------------------------------------------------+
21*/
22
23/* $Id$ */
24
25#ifdef HAVE_CONFIG_H
26#include "config.h"
27#endif
28
29#include "php.h"
30#include "php_globals.h"
31
32#include "ext/standard/info.h"
33#include "ext/standard/php_string.h"
34#include "ext/standard/php_standard.h"
35
36#include "php_odbc.h"
37#include "php_odbc_includes.h"
38#include "php_globals.h"
39
40#if HAVE_UODBC
41
42#include <fcntl.h>
43#include "ext/standard/head.h"
44#include "php_ini.h"
45
46#ifdef PHP_WIN32
47#include <winsock2.h>
48
49#define ODBC_TYPE "Win32"
50#define PHP_ODBC_TYPE ODBC_TYPE
51
52#endif
53
54/*
55 * not defined elsewhere
56 */
57
58#ifndef TRUE
59#define TRUE 1
60#define FALSE 0
61#endif
62
63void odbc_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent);
64
65static int le_result, le_conn, le_pconn;
66
67#define SAFE_SQL_NTS(n) ((SQLSMALLINT) ((n)?(SQL_NTS):0))
68
69/* {{{ arginfo */
70ZEND_BEGIN_ARG_INFO(arginfo_odbc_close_all, 0)
71ZEND_END_ARG_INFO()
72
73ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_binmode, 0, 0, 2)
74	ZEND_ARG_INFO(0, result_id)
75	ZEND_ARG_INFO(0, mode)
76ZEND_END_ARG_INFO()
77
78ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_longreadlen, 0, 0, 2)
79	ZEND_ARG_INFO(0, result_id)
80	ZEND_ARG_INFO(0, length)
81ZEND_END_ARG_INFO()
82
83ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_prepare, 0, 0, 2)
84	ZEND_ARG_INFO(0, connection_id)
85	ZEND_ARG_INFO(0, query)
86ZEND_END_ARG_INFO()
87
88ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_execute, 0, 0, 1)
89	ZEND_ARG_INFO(0, result_id)
90	ZEND_ARG_INFO(0, parameters_array)
91ZEND_END_ARG_INFO()
92
93ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_cursor, 0, 0, 1)
94	ZEND_ARG_INFO(0, result_id)
95ZEND_END_ARG_INFO()
96
97#ifdef HAVE_SQLDATASOURCES
98ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_data_source, 0, 0, 2)
99	ZEND_ARG_INFO(0, connection_id)
100	ZEND_ARG_INFO(0, fetch_type)
101ZEND_END_ARG_INFO()
102#endif
103
104ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_exec, 0, 0, 2)
105	ZEND_ARG_INFO(0, connection_id)
106	ZEND_ARG_INFO(0, query)
107	ZEND_ARG_INFO(0, flags)
108ZEND_END_ARG_INFO()
109
110#ifdef PHP_ODBC_HAVE_FETCH_HASH
111ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_fetch_object, 0, 0, 1)
112	ZEND_ARG_INFO(0, result)
113	ZEND_ARG_INFO(0, rownumber)
114ZEND_END_ARG_INFO()
115
116ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_fetch_array, 0, 0, 1)
117	ZEND_ARG_INFO(0, result)
118	ZEND_ARG_INFO(0, rownumber)
119ZEND_END_ARG_INFO()
120#endif
121
122ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_fetch_into, 0, 0, 2)
123	ZEND_ARG_INFO(0, result_id)
124	ZEND_ARG_INFO(1, result_array)
125	ZEND_ARG_INFO(0, rownumber)
126ZEND_END_ARG_INFO()
127
128ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_fetch_row, 0, 0, 1)
129	ZEND_ARG_INFO(0, result_id)
130	ZEND_ARG_INFO(0, row_number)
131ZEND_END_ARG_INFO()
132
133ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_result, 0, 0, 2)
134	ZEND_ARG_INFO(0, result_id)
135	ZEND_ARG_INFO(0, field)
136ZEND_END_ARG_INFO()
137
138ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_result_all, 0, 0, 1)
139	ZEND_ARG_INFO(0, result_id)
140	ZEND_ARG_INFO(0, format)
141ZEND_END_ARG_INFO()
142
143ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_free_result, 0, 0, 1)
144	ZEND_ARG_INFO(0, result_id)
145ZEND_END_ARG_INFO()
146
147ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_connect, 0, 0, 3)
148	ZEND_ARG_INFO(0, dsn)
149	ZEND_ARG_INFO(0, user)
150	ZEND_ARG_INFO(0, password)
151	ZEND_ARG_INFO(0, cursor_option)
152ZEND_END_ARG_INFO()
153
154ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_pconnect, 0, 0, 3)
155	ZEND_ARG_INFO(0, dsn)
156	ZEND_ARG_INFO(0, user)
157	ZEND_ARG_INFO(0, password)
158	ZEND_ARG_INFO(0, cursor_option)
159ZEND_END_ARG_INFO()
160
161ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_close, 0, 0, 1)
162	ZEND_ARG_INFO(0, connection_id)
163ZEND_END_ARG_INFO()
164
165ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_num_rows, 0, 0, 1)
166	ZEND_ARG_INFO(0, result_id)
167ZEND_END_ARG_INFO()
168
169#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30)
170ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_next_result, 0, 0, 1)
171	ZEND_ARG_INFO(0, result_id)
172ZEND_END_ARG_INFO()
173#endif
174
175ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_num_fields, 0, 0, 1)
176	ZEND_ARG_INFO(0, result_id)
177ZEND_END_ARG_INFO()
178
179ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_field_name, 0, 0, 2)
180	ZEND_ARG_INFO(0, result_id)
181	ZEND_ARG_INFO(0, field_number)
182ZEND_END_ARG_INFO()
183
184ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_field_type, 0, 0, 2)
185	ZEND_ARG_INFO(0, result_id)
186	ZEND_ARG_INFO(0, field_number)
187ZEND_END_ARG_INFO()
188
189ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_field_len, 0, 0, 2)
190	ZEND_ARG_INFO(0, result_id)
191	ZEND_ARG_INFO(0, field_number)
192ZEND_END_ARG_INFO()
193
194ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_field_scale, 0, 0, 2)
195	ZEND_ARG_INFO(0, result_id)
196	ZEND_ARG_INFO(0, field_number)
197ZEND_END_ARG_INFO()
198
199ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_field_num, 0, 0, 2)
200	ZEND_ARG_INFO(0, result_id)
201	ZEND_ARG_INFO(0, field_name)
202ZEND_END_ARG_INFO()
203
204ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_autocommit, 0, 0, 1)
205	ZEND_ARG_INFO(0, connection_id)
206	ZEND_ARG_INFO(0, onoff)
207ZEND_END_ARG_INFO()
208
209ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_commit, 0, 0, 1)
210	ZEND_ARG_INFO(0, connection_id)
211ZEND_END_ARG_INFO()
212
213ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_rollback, 0, 0, 1)
214	ZEND_ARG_INFO(0, connection_id)
215ZEND_END_ARG_INFO()
216
217ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_error, 0, 0, 0)
218	ZEND_ARG_INFO(0, connection_id)
219ZEND_END_ARG_INFO()
220
221ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_errormsg, 0, 0, 0)
222	ZEND_ARG_INFO(0, connection_id)
223ZEND_END_ARG_INFO()
224
225ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_setoption, 0, 0, 4)
226	ZEND_ARG_INFO(0, conn_id)
227	ZEND_ARG_INFO(0, which)
228	ZEND_ARG_INFO(0, option)
229	ZEND_ARG_INFO(0, value)
230ZEND_END_ARG_INFO()
231
232ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_tables, 0, 0, 1)
233	ZEND_ARG_INFO(0, connection_id)
234	ZEND_ARG_INFO(0, qualifier)
235	ZEND_ARG_INFO(0, owner)
236	ZEND_ARG_INFO(0, name)
237	ZEND_ARG_INFO(0, table_types)
238ZEND_END_ARG_INFO()
239
240ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_columns, 0, 0, 1)
241	ZEND_ARG_INFO(0, connection_id)
242	ZEND_ARG_INFO(0, qualifier)
243	ZEND_ARG_INFO(0, owner)
244	ZEND_ARG_INFO(0, table_name)
245	ZEND_ARG_INFO(0, column_name)
246ZEND_END_ARG_INFO()
247
248ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_gettypeinfo, 0, 0, 1)
249	ZEND_ARG_INFO(0, connection_id)
250	ZEND_ARG_INFO(0, data_type)
251ZEND_END_ARG_INFO()
252
253ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_primarykeys, 0, 0, 4)
254	ZEND_ARG_INFO(0, connection_id)
255	ZEND_ARG_INFO(0, qualifier)
256	ZEND_ARG_INFO(0, owner)
257	ZEND_ARG_INFO(0, table)
258ZEND_END_ARG_INFO()
259
260#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) && !defined(HAVE_SOLID_35)
261#if !defined(HAVE_BIRDSTEP)
262ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_procedurecolumns, 0, 0, 1)
263	ZEND_ARG_INFO(0, connection_id)
264	ZEND_ARG_INFO(0, qualifier)
265	ZEND_ARG_INFO(0, owner)
266	ZEND_ARG_INFO(0, proc)
267	ZEND_ARG_INFO(0, column)
268ZEND_END_ARG_INFO()
269#endif
270
271ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_procedures, 0, 0, 1)
272	ZEND_ARG_INFO(0, connection_id)
273	ZEND_ARG_INFO(0, qualifier)
274	ZEND_ARG_INFO(0, owner)
275	ZEND_ARG_INFO(0, name)
276ZEND_END_ARG_INFO()
277
278ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_foreignkeys, 0, 0, 7)
279	ZEND_ARG_INFO(0, connection_id)
280	ZEND_ARG_INFO(0, pk_qualifier)
281	ZEND_ARG_INFO(0, pk_owner)
282	ZEND_ARG_INFO(0, pk_table)
283	ZEND_ARG_INFO(0, fk_qualifier)
284	ZEND_ARG_INFO(0, fk_owner)
285	ZEND_ARG_INFO(0, fk_table)
286ZEND_END_ARG_INFO()
287#endif
288
289ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_specialcolumns, 0, 0, 7)
290	ZEND_ARG_INFO(0, connection_id)
291	ZEND_ARG_INFO(0, type)
292	ZEND_ARG_INFO(0, qualifier)
293	ZEND_ARG_INFO(0, owner)
294	ZEND_ARG_INFO(0, table)
295	ZEND_ARG_INFO(0, scope)
296	ZEND_ARG_INFO(0, nullable)
297ZEND_END_ARG_INFO()
298
299ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_statistics, 0, 0, 6)
300	ZEND_ARG_INFO(0, connection_id)
301	ZEND_ARG_INFO(0, qualifier)
302	ZEND_ARG_INFO(0, owner)
303	ZEND_ARG_INFO(0, name)
304	ZEND_ARG_INFO(0, unique)
305	ZEND_ARG_INFO(0, accuracy)
306ZEND_END_ARG_INFO()
307
308#if !defined(HAVE_DBMAKER) && !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) &&!defined(HAVE_SOLID_35) && !defined(HAVE_BIRDSTEP)
309ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_tableprivileges, 0, 0, 4)
310	ZEND_ARG_INFO(0, connection_id)
311	ZEND_ARG_INFO(0, qualifier)
312	ZEND_ARG_INFO(0, owner)
313	ZEND_ARG_INFO(0, name)
314ZEND_END_ARG_INFO()
315
316ZEND_BEGIN_ARG_INFO_EX(arginfo_odbc_columnprivileges, 0, 0, 5)
317	ZEND_ARG_INFO(0, connection_id)
318	ZEND_ARG_INFO(0, catalog)
319	ZEND_ARG_INFO(0, schema)
320	ZEND_ARG_INFO(0, table)
321	ZEND_ARG_INFO(0, column)
322ZEND_END_ARG_INFO()
323#endif
324/* }}} */
325
326/* {{{ odbc_functions[]
327 */
328const zend_function_entry odbc_functions[] = {
329	PHP_FE(odbc_autocommit, arginfo_odbc_autocommit)
330	PHP_FE(odbc_binmode, arginfo_odbc_binmode)
331	PHP_FE(odbc_close, arginfo_odbc_close)
332	PHP_FE(odbc_close_all, arginfo_odbc_close_all)
333	PHP_FE(odbc_columns, arginfo_odbc_columns)
334	PHP_FE(odbc_commit, arginfo_odbc_commit)
335	PHP_FE(odbc_connect, arginfo_odbc_connect)
336	PHP_FE(odbc_cursor, arginfo_odbc_cursor)
337#ifdef HAVE_SQLDATASOURCES
338	PHP_FE(odbc_data_source, arginfo_odbc_data_source)
339#endif
340	PHP_FE(odbc_execute, arginfo_odbc_execute)
341	PHP_FE(odbc_error, arginfo_odbc_error)
342	PHP_FE(odbc_errormsg, arginfo_odbc_errormsg)
343	PHP_FE(odbc_exec, arginfo_odbc_exec)
344#ifdef PHP_ODBC_HAVE_FETCH_HASH
345	PHP_FE(odbc_fetch_array, arginfo_odbc_fetch_array)
346	PHP_FE(odbc_fetch_object, arginfo_odbc_fetch_object)
347#endif
348	PHP_FE(odbc_fetch_row, arginfo_odbc_fetch_row)
349	PHP_FE(odbc_fetch_into, arginfo_odbc_fetch_into)
350	PHP_FE(odbc_field_len, arginfo_odbc_field_len)
351	PHP_FE(odbc_field_scale, arginfo_odbc_field_scale)
352	PHP_FE(odbc_field_name, arginfo_odbc_field_name)
353	PHP_FE(odbc_field_type, arginfo_odbc_field_type)
354	PHP_FE(odbc_field_num, arginfo_odbc_field_num)
355	PHP_FE(odbc_free_result, arginfo_odbc_free_result)
356	PHP_FE(odbc_gettypeinfo, arginfo_odbc_gettypeinfo)
357	PHP_FE(odbc_longreadlen, arginfo_odbc_longreadlen)
358#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30)
359	PHP_FE(odbc_next_result, arginfo_odbc_next_result)
360#endif
361	PHP_FE(odbc_num_fields, arginfo_odbc_num_fields)
362	PHP_FE(odbc_num_rows, arginfo_odbc_num_rows)
363	PHP_FE(odbc_pconnect, arginfo_odbc_pconnect)
364	PHP_FE(odbc_prepare, arginfo_odbc_prepare)
365	PHP_FE(odbc_result, arginfo_odbc_result)
366	PHP_FE(odbc_result_all, arginfo_odbc_result_all)
367	PHP_FE(odbc_rollback, arginfo_odbc_rollback)
368	PHP_FE(odbc_setoption, arginfo_odbc_setoption)
369	PHP_FE(odbc_specialcolumns, arginfo_odbc_specialcolumns)
370	PHP_FE(odbc_statistics, arginfo_odbc_statistics)
371	PHP_FE(odbc_tables, arginfo_odbc_tables)
372	PHP_FE(odbc_primarykeys, arginfo_odbc_primarykeys)
373#if !defined(HAVE_DBMAKER) && !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) &&!defined(HAVE_SOLID_35) && !defined(HAVE_BIRDSTEP)    /* not supported now */
374	PHP_FE(odbc_columnprivileges, arginfo_odbc_columnprivileges)
375	PHP_FE(odbc_tableprivileges, arginfo_odbc_tableprivileges)
376#endif
377#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) && !defined(HAVE_SOLID_35) /* not supported */
378	PHP_FE(odbc_foreignkeys, arginfo_odbc_foreignkeys)
379	PHP_FE(odbc_procedures, arginfo_odbc_procedures)
380#if !defined(HAVE_BIRDSTEP)
381	PHP_FE(odbc_procedurecolumns, arginfo_odbc_procedurecolumns)
382#endif
383#endif
384	PHP_FALIAS(odbc_do, odbc_exec, arginfo_odbc_exec)
385	PHP_FALIAS(odbc_field_precision, odbc_field_len, arginfo_odbc_field_len)
386	PHP_FE_END
387};
388/* }}} */
389
390PHP_ODBC_API ZEND_DECLARE_MODULE_GLOBALS(odbc)
391static PHP_GINIT_FUNCTION(odbc);
392
393/* {{{ odbc_module_entry
394 */
395zend_module_entry odbc_module_entry = {
396	STANDARD_MODULE_HEADER,
397	"odbc",
398	odbc_functions,
399	PHP_MINIT(odbc),
400	PHP_MSHUTDOWN(odbc),
401	PHP_RINIT(odbc),
402	PHP_RSHUTDOWN(odbc),
403	PHP_MINFO(odbc),
404	PHP_ODBC_VERSION,
405	PHP_MODULE_GLOBALS(odbc),
406	PHP_GINIT(odbc),
407	NULL,
408	NULL,
409	STANDARD_MODULE_PROPERTIES_EX
410};
411/* }}} */
412
413#ifdef COMPILE_DL_ODBC
414#ifdef ZTS
415ZEND_TSRMLS_CACHE_DEFINE()
416#endif
417ZEND_GET_MODULE(odbc)
418#endif
419
420/* {{{ _free_odbc_result
421 */
422static void _free_odbc_result(zend_resource *rsrc)
423{
424	odbc_result *res = (odbc_result *)rsrc->ptr;
425	int i;
426	RETCODE rc;
427
428	if (res) {
429		if (res->values) {
430			for(i = 0; i < res->numcols; i++) {
431				if (res->values[i].value)
432					efree(res->values[i].value);
433			}
434			efree(res->values);
435			res->values = NULL;
436		}
437		/* If aborted via timer expiration, don't try to call any unixODBC function */
438		if (res->stmt && !(PG(connection_status) & PHP_CONNECTION_TIMEOUT)) {
439#if defined(HAVE_SOLID) || defined(HAVE_SOLID_30) || defined(HAVE_SOLID_35)
440			SQLTransact(res->conn_ptr->henv, res->conn_ptr->hdbc,
441						(SQLUSMALLINT) SQL_COMMIT);
442#endif
443			rc = SQLFreeStmt(res->stmt,SQL_DROP);
444			/* We don't want the connection to be closed after the last statement has been closed
445			 * Connections will be closed on shutdown
446			 * zend_list_delete(res->conn_ptr->id);
447			 */
448		}
449		if (res->param_info) {
450			efree(res->param_info);
451		}
452		efree(res);
453	}
454}
455/* }}} */
456
457/* {{{ safe_odbc_disconnect
458 * disconnect, and if it fails, then issue a rollback for any pending transaction (lurcher)
459 */
460static void safe_odbc_disconnect( void *handle )
461{
462	int ret;
463
464	ret = SQLDisconnect( handle );
465	if ( ret == SQL_ERROR )
466	{
467		SQLTransact( NULL, handle, SQL_ROLLBACK );
468		SQLDisconnect( handle );
469	}
470}
471/* }}} */
472
473/* {{{ _close_odbc_conn
474 */
475static void _close_odbc_conn(zend_resource *rsrc)
476{
477	zend_resource *p;
478	odbc_result *res;
479
480	odbc_connection *conn = (odbc_connection *)rsrc->ptr;
481
482	ZEND_HASH_FOREACH_PTR(&EG(regular_list), p) {
483		if (p->ptr && (p->type == le_result)) {
484			res = (odbc_result *)p->ptr;
485			if (res->conn_ptr == conn) {
486				zend_list_close(p);
487			}
488		}
489	} ZEND_HASH_FOREACH_END();
490
491	/* If aborted via timer expiration, don't try to call any unixODBC function */
492	if (!(PG(connection_status) & PHP_CONNECTION_TIMEOUT)) {
493		safe_odbc_disconnect(conn->hdbc);
494		SQLFreeConnect(conn->hdbc);
495		SQLFreeEnv(conn->henv);
496	}
497	efree(conn);
498	ODBCG(num_links)--;
499}
500/* }}} */
501
502/* {{{ void _close_odbc_pconn
503 */
504static void _close_odbc_pconn(zend_resource *rsrc)
505{
506	zend_resource *p;
507	odbc_result *res;
508	odbc_connection *conn = (odbc_connection *)rsrc->ptr;
509
510	ZEND_HASH_FOREACH_PTR(&EG(regular_list), p) {
511		if (p->ptr && (p->type == le_result)) {
512			res = (odbc_result *)p->ptr;
513			if (res->conn_ptr == conn) {
514				zend_list_close(p);
515			}
516		}
517	} ZEND_HASH_FOREACH_END();
518
519	/* If aborted via timer expiration, don't try to call any unixODBC function */
520	if (!(PG(connection_status) & PHP_CONNECTION_TIMEOUT)) {
521		safe_odbc_disconnect(conn->hdbc);
522		SQLFreeConnect(conn->hdbc);
523		SQLFreeEnv(conn->henv);
524	}
525	free(conn);
526
527	ODBCG(num_links)--;
528	ODBCG(num_persistent)--;
529}
530/* }}} */
531
532/* {{{ PHP_INI_DISP(display_link_nums)
533 */
534static PHP_INI_DISP(display_link_nums)
535{
536	char *value;
537
538	if (type == PHP_INI_DISPLAY_ORIG && ini_entry->modified) {
539		value = ZSTR_VAL(ini_entry->orig_value);
540	} else if (ini_entry->value) {
541		value = ZSTR_VAL(ini_entry->value);
542	} else {
543		value = NULL;
544	}
545
546	if (value) {
547		if (atoi(value) == -1) {
548			PUTS("Unlimited");
549		} else {
550			php_printf("%s", value);
551		}
552	}
553}
554/* }}} */
555
556/* {{{ PHP_INI_DISP(display_defPW)
557 */
558static PHP_INI_DISP(display_defPW)
559{
560	char *value;
561
562	if (type == PHP_INI_DISPLAY_ORIG && ini_entry->modified) {
563		value = ZSTR_VAL(ini_entry->orig_value);
564	} else if (ini_entry->value) {
565		value = ZSTR_VAL(ini_entry->value);
566	} else {
567		value = NULL;
568	}
569
570	if (value) {
571#if PHP_DEBUG
572		php_printf("%s", value);
573#else
574		PUTS("********");
575#endif
576	} else {
577		if (PG(html_errors)) {
578			PUTS("<i>no value</i>");
579		} else {
580			PUTS("no value");
581		}
582	}
583}
584/* }}} */
585
586/* {{{ PHP_INI_DISP(display_binmode)
587 */
588static PHP_INI_DISP(display_binmode)
589{
590	char *value;
591
592	if (type == PHP_INI_DISPLAY_ORIG && ini_entry->modified) {
593		value = ZSTR_VAL(ini_entry->orig_value);
594	} else if (ini_entry->value) {
595		value = ZSTR_VAL(ini_entry->value);
596	} else {
597		value = NULL;
598	}
599
600	if (value) {
601		switch(atoi(value)) {
602			case 0:
603				PUTS("passthru");
604				break;
605			case 1:
606				PUTS("return as is");
607				break;
608			case 2:
609				PUTS("return as char");
610				break;
611		}
612	}
613}
614/* }}} */
615
616/* {{{ PHP_INI_DISP(display_lrl)
617 */
618static PHP_INI_DISP(display_lrl)
619{
620	char *value;
621
622	if (type == PHP_INI_DISPLAY_ORIG && ini_entry->modified) {
623		value = ZSTR_VAL(ini_entry->orig_value);
624	} else if (ini_entry->value) {
625		value = ZSTR_VAL(ini_entry->value);
626	} else {
627		value = NULL;
628	}
629
630	if (value) {
631		if (atoi(value) <= 0) {
632			PUTS("Passthru");
633		} else {
634			php_printf("return up to %s bytes", value);
635		}
636	}
637}
638/* }}} */
639
640
641/* {{{ PHP_INI_DISP(display_cursortype)
642 */
643static PHP_INI_DISP(display_cursortype)
644{
645	char *value;
646
647	if (type == PHP_INI_DISPLAY_ORIG && ini_entry->modified) {
648		value = ZSTR_VAL(ini_entry->orig_value);
649	} else if (ini_entry->value) {
650		value = ZSTR_VAL(ini_entry->value);
651	} else {
652		value = NULL;
653	}
654
655	if (value) {
656		switch (atoi (value))
657		  {
658		    case SQL_CURSOR_FORWARD_ONLY:
659				PUTS ("Forward Only cursor");
660				break;
661
662			case SQL_CURSOR_STATIC:
663			    PUTS ("Static cursor");
664				break;
665
666			case SQL_CURSOR_KEYSET_DRIVEN:
667				PUTS ("Keyset driven cursor");
668				break;
669
670			case SQL_CURSOR_DYNAMIC:
671				PUTS ("Dynamic cursor");
672				break;
673
674			default:
675				php_printf("Unknown cursor model %s", value);
676				break;
677		  }
678	}
679}
680
681/* }}} */
682
683/* {{{ PHP_INI_BEGIN
684 */
685PHP_INI_BEGIN()
686	STD_PHP_INI_BOOLEAN("odbc.allow_persistent", "1", PHP_INI_SYSTEM, OnUpdateLong,
687			allow_persistent, zend_odbc_globals, odbc_globals)
688	STD_PHP_INI_ENTRY_EX("odbc.max_persistent",  "-1", PHP_INI_SYSTEM, OnUpdateLong,
689			max_persistent, zend_odbc_globals, odbc_globals, display_link_nums)
690	STD_PHP_INI_ENTRY_EX("odbc.max_links", "-1", PHP_INI_SYSTEM, OnUpdateLong,
691			max_links, zend_odbc_globals, odbc_globals, display_link_nums)
692	STD_PHP_INI_ENTRY("odbc.default_db", NULL, PHP_INI_ALL, OnUpdateString,
693			defDB, zend_odbc_globals, odbc_globals)
694	STD_PHP_INI_ENTRY("odbc.default_user", NULL, PHP_INI_ALL, OnUpdateString,
695			defUser, zend_odbc_globals, odbc_globals)
696	STD_PHP_INI_ENTRY_EX("odbc.default_pw", NULL, PHP_INI_ALL, OnUpdateString,
697			defPW, zend_odbc_globals, odbc_globals, display_defPW)
698	STD_PHP_INI_ENTRY_EX("odbc.defaultlrl", "4096", PHP_INI_ALL, OnUpdateLong,
699			defaultlrl, zend_odbc_globals, odbc_globals, display_lrl)
700	STD_PHP_INI_ENTRY_EX("odbc.defaultbinmode", "1", PHP_INI_ALL, OnUpdateLong,
701			defaultbinmode, zend_odbc_globals, odbc_globals, display_binmode)
702	STD_PHP_INI_BOOLEAN("odbc.check_persistent", "1", PHP_INI_SYSTEM, OnUpdateLong,
703			check_persistent, zend_odbc_globals, odbc_globals)
704	STD_PHP_INI_ENTRY_EX("odbc.default_cursortype", "3", PHP_INI_ALL, OnUpdateLong,
705			default_cursortype, zend_odbc_globals, odbc_globals, display_cursortype)
706PHP_INI_END()
707/* }}} */
708
709static PHP_GINIT_FUNCTION(odbc)
710{
711#if defined(COMPILE_DL_ODBC) && defined(ZTS)
712	ZEND_TSRMLS_CACHE_UPDATE();
713#endif
714	odbc_globals->num_persistent = 0;
715}
716
717/* {{{ PHP_MINIT_FUNCTION */
718PHP_MINIT_FUNCTION(odbc)
719{
720#ifdef SQLANY_BUG
721	ODBC_SQL_CONN_T foobar;
722	RETCODE rc;
723#endif
724
725	REGISTER_INI_ENTRIES();
726	le_result = zend_register_list_destructors_ex(_free_odbc_result, NULL, "odbc result", module_number);
727	le_conn = zend_register_list_destructors_ex(_close_odbc_conn, NULL, "odbc link", module_number);
728	le_pconn = zend_register_list_destructors_ex(NULL, _close_odbc_pconn, "odbc link persistent", module_number);
729	odbc_module_entry.type = type;
730
731	REGISTER_STRING_CONSTANT("ODBC_TYPE", PHP_ODBC_TYPE, CONST_CS | CONST_PERSISTENT);
732	REGISTER_LONG_CONSTANT("ODBC_BINMODE_PASSTHRU", 0, CONST_CS | CONST_PERSISTENT);
733	REGISTER_LONG_CONSTANT("ODBC_BINMODE_RETURN", 1, CONST_CS | CONST_PERSISTENT);
734	REGISTER_LONG_CONSTANT("ODBC_BINMODE_CONVERT", 2, CONST_CS | CONST_PERSISTENT);
735	/* Define Constants for options
736	   these Constants are defined in <sqlext.h>
737	*/
738	REGISTER_LONG_CONSTANT("SQL_ODBC_CURSORS", SQL_ODBC_CURSORS, CONST_PERSISTENT | CONST_CS);
739	REGISTER_LONG_CONSTANT("SQL_CUR_USE_DRIVER", SQL_CUR_USE_DRIVER, CONST_PERSISTENT | CONST_CS);
740	REGISTER_LONG_CONSTANT("SQL_CUR_USE_IF_NEEDED", SQL_CUR_USE_IF_NEEDED, CONST_PERSISTENT | CONST_CS);
741	REGISTER_LONG_CONSTANT("SQL_CUR_USE_ODBC", SQL_CUR_USE_ODBC, CONST_PERSISTENT | CONST_CS);
742
743
744	REGISTER_LONG_CONSTANT("SQL_CONCURRENCY", SQL_CONCURRENCY, CONST_PERSISTENT | CONST_CS);
745	REGISTER_LONG_CONSTANT("SQL_CONCUR_READ_ONLY", SQL_CONCUR_READ_ONLY, CONST_PERSISTENT | CONST_CS);
746	REGISTER_LONG_CONSTANT("SQL_CONCUR_LOCK", SQL_CONCUR_LOCK, CONST_PERSISTENT | CONST_CS);
747	REGISTER_LONG_CONSTANT("SQL_CONCUR_ROWVER", SQL_CONCUR_ROWVER, CONST_PERSISTENT | CONST_CS);
748	REGISTER_LONG_CONSTANT("SQL_CONCUR_VALUES", SQL_CONCUR_VALUES, CONST_PERSISTENT | CONST_CS);
749
750	REGISTER_LONG_CONSTANT("SQL_CURSOR_TYPE", SQL_CURSOR_TYPE, CONST_PERSISTENT | CONST_CS);
751	REGISTER_LONG_CONSTANT("SQL_CURSOR_FORWARD_ONLY", SQL_CURSOR_FORWARD_ONLY, CONST_PERSISTENT | CONST_CS);
752	REGISTER_LONG_CONSTANT("SQL_CURSOR_KEYSET_DRIVEN", SQL_CURSOR_KEYSET_DRIVEN, CONST_PERSISTENT | CONST_CS);
753	REGISTER_LONG_CONSTANT("SQL_CURSOR_DYNAMIC", SQL_CURSOR_DYNAMIC, CONST_PERSISTENT | CONST_CS);
754	REGISTER_LONG_CONSTANT("SQL_CURSOR_STATIC", SQL_CURSOR_STATIC, CONST_PERSISTENT | CONST_CS);
755
756	REGISTER_LONG_CONSTANT("SQL_KEYSET_SIZE", SQL_KEYSET_SIZE, CONST_PERSISTENT | CONST_CS);
757
758	/* these are for the Data Source type */
759	REGISTER_LONG_CONSTANT("SQL_FETCH_FIRST", SQL_FETCH_FIRST, CONST_PERSISTENT | CONST_CS);
760	REGISTER_LONG_CONSTANT("SQL_FETCH_NEXT", SQL_FETCH_NEXT, CONST_PERSISTENT | CONST_CS);
761
762	/*
763	 * register the standard data types
764	 */
765	REGISTER_LONG_CONSTANT("SQL_CHAR", SQL_CHAR, CONST_PERSISTENT | CONST_CS);
766	REGISTER_LONG_CONSTANT("SQL_VARCHAR", SQL_VARCHAR, CONST_PERSISTENT | CONST_CS);
767	REGISTER_LONG_CONSTANT("SQL_LONGVARCHAR", SQL_LONGVARCHAR, CONST_PERSISTENT | CONST_CS);
768	REGISTER_LONG_CONSTANT("SQL_DECIMAL", SQL_DECIMAL, CONST_PERSISTENT | CONST_CS);
769	REGISTER_LONG_CONSTANT("SQL_NUMERIC", SQL_NUMERIC, CONST_PERSISTENT | CONST_CS);
770	REGISTER_LONG_CONSTANT("SQL_BIT", SQL_BIT, CONST_PERSISTENT | CONST_CS);
771	REGISTER_LONG_CONSTANT("SQL_TINYINT", SQL_TINYINT, CONST_PERSISTENT | CONST_CS);
772	REGISTER_LONG_CONSTANT("SQL_SMALLINT", SQL_SMALLINT, CONST_PERSISTENT | CONST_CS);
773	REGISTER_LONG_CONSTANT("SQL_INTEGER", SQL_INTEGER, CONST_PERSISTENT | CONST_CS);
774	REGISTER_LONG_CONSTANT("SQL_BIGINT", SQL_BIGINT, CONST_PERSISTENT | CONST_CS);
775	REGISTER_LONG_CONSTANT("SQL_REAL", SQL_REAL, CONST_PERSISTENT | CONST_CS);
776	REGISTER_LONG_CONSTANT("SQL_FLOAT", SQL_FLOAT, CONST_PERSISTENT | CONST_CS);
777	REGISTER_LONG_CONSTANT("SQL_DOUBLE", SQL_DOUBLE, CONST_PERSISTENT | CONST_CS);
778	REGISTER_LONG_CONSTANT("SQL_BINARY", SQL_BINARY, CONST_PERSISTENT | CONST_CS);
779	REGISTER_LONG_CONSTANT("SQL_VARBINARY", SQL_VARBINARY, CONST_PERSISTENT | CONST_CS);
780	REGISTER_LONG_CONSTANT("SQL_LONGVARBINARY", SQL_LONGVARBINARY, CONST_PERSISTENT | CONST_CS);
781	REGISTER_LONG_CONSTANT("SQL_DATE", SQL_DATE, CONST_PERSISTENT | CONST_CS);
782	REGISTER_LONG_CONSTANT("SQL_TIME", SQL_TIME, CONST_PERSISTENT | CONST_CS);
783	REGISTER_LONG_CONSTANT("SQL_TIMESTAMP", SQL_TIMESTAMP, CONST_PERSISTENT | CONST_CS);
784#if defined(ODBCVER) && (ODBCVER >= 0x0300)
785	REGISTER_LONG_CONSTANT("SQL_TYPE_DATE", SQL_TYPE_DATE, CONST_PERSISTENT | CONST_CS);
786	REGISTER_LONG_CONSTANT("SQL_TYPE_TIME", SQL_TYPE_TIME, CONST_PERSISTENT | CONST_CS);
787	REGISTER_LONG_CONSTANT("SQL_TYPE_TIMESTAMP", SQL_TYPE_TIMESTAMP, CONST_PERSISTENT | CONST_CS);
788	REGISTER_LONG_CONSTANT("SQL_WCHAR", SQL_WCHAR, CONST_PERSISTENT | CONST_CS);
789	REGISTER_LONG_CONSTANT("SQL_WVARCHAR", SQL_WVARCHAR, CONST_PERSISTENT | CONST_CS);
790	REGISTER_LONG_CONSTANT("SQL_WLONGVARCHAR", SQL_WLONGVARCHAR, CONST_PERSISTENT | CONST_CS);
791
792	/*
793	 * SQLSpecialColumns values
794	 */
795	REGISTER_LONG_CONSTANT("SQL_BEST_ROWID", SQL_BEST_ROWID, CONST_PERSISTENT | CONST_CS);
796	REGISTER_LONG_CONSTANT("SQL_ROWVER", SQL_ROWVER, CONST_PERSISTENT | CONST_CS);
797	REGISTER_LONG_CONSTANT("SQL_SCOPE_CURROW", SQL_SCOPE_CURROW, CONST_PERSISTENT | CONST_CS);
798	REGISTER_LONG_CONSTANT("SQL_SCOPE_TRANSACTION", SQL_SCOPE_TRANSACTION, CONST_PERSISTENT | CONST_CS);
799	REGISTER_LONG_CONSTANT("SQL_SCOPE_SESSION", SQL_SCOPE_SESSION, CONST_PERSISTENT | CONST_CS);
800	REGISTER_LONG_CONSTANT("SQL_NO_NULLS", SQL_NO_NULLS, CONST_PERSISTENT | CONST_CS);
801	REGISTER_LONG_CONSTANT("SQL_NULLABLE", SQL_NULLABLE, CONST_PERSISTENT | CONST_CS);
802
803	/*
804	 * SQLStatistics values
805	 */
806	REGISTER_LONG_CONSTANT("SQL_INDEX_UNIQUE", SQL_INDEX_UNIQUE, CONST_PERSISTENT | CONST_CS);
807	REGISTER_LONG_CONSTANT("SQL_INDEX_ALL", SQL_INDEX_ALL, CONST_PERSISTENT | CONST_CS);
808	REGISTER_LONG_CONSTANT("SQL_ENSURE", SQL_ENSURE, CONST_PERSISTENT | CONST_CS);
809	REGISTER_LONG_CONSTANT("SQL_QUICK", SQL_QUICK, CONST_PERSISTENT | CONST_CS);
810#endif
811
812#if defined(HAVE_IBMDB2) && defined(_AIX)
813	/* atexit() handler in the DB2/AIX library segfaults in PHP CLI */
814	/* DB2NOEXITLIST env variable prevents DB2 from invoking atexit() */
815	putenv("DB2NOEXITLIST=TRUE");
816#endif
817
818	return SUCCESS;
819}
820/* }}} */
821
822/* {{{ PHP_RINIT_FUNCTION */
823PHP_RINIT_FUNCTION(odbc)
824{
825	ODBCG(defConn) = -1;
826	ODBCG(num_links) = ODBCG(num_persistent);
827	memset(ODBCG(laststate), '\0', 6);
828	memset(ODBCG(lasterrormsg), '\0', SQL_MAX_MESSAGE_LENGTH);
829	return SUCCESS;
830}
831/* }}} */
832
833/* {{{ PHP_RSHUTDOWN_FUNCTION */
834PHP_RSHUTDOWN_FUNCTION(odbc)
835{
836	return SUCCESS;
837}
838/* }}} */
839
840/* {{{ PHP_MSHUTDOWN_FUNCTION */
841PHP_MSHUTDOWN_FUNCTION(odbc)
842{
843	UNREGISTER_INI_ENTRIES();
844	return SUCCESS;
845}
846/* }}} */
847
848/* {{{ PHP_MINFO_FUNCTION */
849PHP_MINFO_FUNCTION(odbc)
850{
851	char buf[32];
852
853	php_info_print_table_start();
854	php_info_print_table_header(2, "ODBC Support", "enabled");
855	snprintf(buf, sizeof(buf), ZEND_LONG_FMT, ODBCG(num_persistent));
856	php_info_print_table_row(2, "Active Persistent Links", buf);
857	snprintf(buf, sizeof(buf), ZEND_LONG_FMT, ODBCG(num_links));
858	php_info_print_table_row(2, "Active Links", buf);
859	php_info_print_table_row(2, "ODBC library", PHP_ODBC_TYPE);
860#ifdef ODBCVER
861	snprintf(buf, sizeof(buf), "0x%0.4x", ODBCVER);
862	php_info_print_table_row(2, "ODBCVER", buf);
863#endif
864#ifndef PHP_WIN32
865	php_info_print_table_row(2, "ODBC_INCLUDE", PHP_ODBC_INCLUDE);
866	php_info_print_table_row(2, "ODBC_LFLAGS", PHP_ODBC_LFLAGS);
867	php_info_print_table_row(2, "ODBC_LIBS", PHP_ODBC_LIBS);
868#endif
869	php_info_print_table_end();
870
871	DISPLAY_INI_ENTRIES();
872
873}
874/* }}} */
875
876/* {{{ odbc_sql_error */
877void odbc_sql_error(ODBC_SQL_ERROR_PARAMS)
878{
879	char   	    state[6];
880	SQLINTEGER	error;        /* Not used */
881	char   	    errormsg[SQL_MAX_MESSAGE_LENGTH];
882	SQLSMALLINT	errormsgsize; /* Not used */
883	RETCODE rc;
884	ODBC_SQL_ENV_T henv;
885	ODBC_SQL_CONN_T conn;
886
887	if (conn_resource) {
888		henv = conn_resource->henv;
889		conn = conn_resource->hdbc;
890	} else {
891		henv = SQL_NULL_HENV;
892		conn = SQL_NULL_HDBC;
893	}
894
895	/* This leads to an endless loop in many drivers!
896	 *
897	   while(henv != SQL_NULL_HENV){
898		do {
899	 */
900	rc = SQLError(henv, conn, stmt, state, &error, errormsg, sizeof(errormsg)-1, &errormsgsize);
901	if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
902		snprintf(state, sizeof(state), "HY000");
903		snprintf(errormsg, sizeof(errormsg), "Failed to fetch error message");
904	}
905	if (conn_resource) {
906		memcpy(conn_resource->laststate, state, sizeof(state));
907		memcpy(conn_resource->lasterrormsg, errormsg, sizeof(errormsg));
908	}
909	memcpy(ODBCG(laststate), state, sizeof(state));
910	memcpy(ODBCG(lasterrormsg), errormsg, sizeof(errormsg));
911	if (func) {
912		php_error_docref(NULL, E_WARNING, "SQL error: %s, SQL state %s in %s", errormsg, state, func);
913	} else {
914		php_error_docref(NULL, E_WARNING, "SQL error: %s, SQL state %s", errormsg, state);
915	}
916	/*
917		} while (SQL_SUCCEEDED(rc));
918	}
919	*/
920}
921/* }}} */
922
923/* {{{ php_odbc_fetch_attribs */
924void php_odbc_fetch_attribs(INTERNAL_FUNCTION_PARAMETERS, int mode)
925{
926	odbc_result *result;
927	zval *pv_res;
928	zend_long flag;
929
930	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &pv_res, &flag) == FAILURE) {
931		return;
932	}
933
934	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
935		RETURN_FALSE;
936	}
937
938	if (mode) {
939		result->longreadlen = flag;
940	} else {
941		result->binmode = flag;
942	}
943
944	RETURN_TRUE;
945}
946/* }}} */
947
948/* {{{ odbc_bindcols */
949int odbc_bindcols(odbc_result *result)
950{
951	RETCODE rc;
952	int i;
953	SQLSMALLINT 	colnamelen; /* Not used */
954	SQLLEN      	displaysize;
955	SQLUSMALLINT	colfieldid;
956	int		charextraalloc;
957
958	result->values = (odbc_result_value *) safe_emalloc(sizeof(odbc_result_value), result->numcols, 0);
959
960	result->longreadlen = ODBCG(defaultlrl);
961	result->binmode = ODBCG(defaultbinmode);
962
963	for(i = 0; i < result->numcols; i++) {
964		charextraalloc = 0;
965		colfieldid = SQL_COLUMN_DISPLAY_SIZE;
966
967		rc = PHP_ODBC_SQLCOLATTRIBUTE(result->stmt, (SQLUSMALLINT)(i+1), PHP_ODBC_SQL_DESC_NAME,
968				result->values[i].name, sizeof(result->values[i].name), &colnamelen, 0);
969		rc = PHP_ODBC_SQLCOLATTRIBUTE(result->stmt, (SQLUSMALLINT)(i+1), SQL_COLUMN_TYPE,
970				NULL, 0, NULL, &result->values[i].coltype);
971
972		/* Don't bind LONG / BINARY columns, so that fetch behaviour can
973		 * be controlled by odbc_binmode() / odbc_longreadlen()
974		 */
975
976		switch(result->values[i].coltype) {
977			case SQL_BINARY:
978			case SQL_VARBINARY:
979			case SQL_LONGVARBINARY:
980			case SQL_LONGVARCHAR:
981#if defined(ODBCVER) && (ODBCVER >= 0x0300)
982			case SQL_WLONGVARCHAR:
983#endif
984				result->values[i].value = NULL;
985				break;
986
987#ifdef HAVE_ADABAS
988			case SQL_TIMESTAMP:
989				result->values[i].value = (char *)emalloc(27);
990				SQLBindCol(result->stmt, (SQLUSMALLINT)(i+1), SQL_C_CHAR, result->values[i].value,
991							27, &result->values[i].vallen);
992				break;
993#endif /* HAVE_ADABAS */
994			case SQL_CHAR:
995			case SQL_VARCHAR:
996#if defined(ODBCVER) && (ODBCVER >= 0x0300)
997			case SQL_WCHAR:
998			case SQL_WVARCHAR:
999				colfieldid = SQL_DESC_OCTET_LENGTH;
1000#else
1001				charextraalloc = 1;
1002#endif
1003			default:
1004				rc = PHP_ODBC_SQLCOLATTRIBUTE(result->stmt, (SQLUSMALLINT)(i+1), colfieldid,
1005								NULL, 0, NULL, &displaysize);
1006#if defined(ODBCVER) && (ODBCVER >= 0x0300)
1007				if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO && colfieldid == SQL_DESC_OCTET_LENGTH) {
1008					SQLINTEGER err;
1009					SQLCHAR errtxt[128];
1010					SQLCHAR state[6];
1011
1012					memset(errtxt, '\0', 128);
1013					memset(state, '\0', 6);
1014
1015					if (SQL_SUCCESS == SQLGetDiagRec(SQL_HANDLE_STMT, result->stmt, 1, state, &err, errtxt, 128, NULL)) {
1016						errtxt[127] = '\0';
1017						state[5] = '\0';
1018						php_error_docref(NULL, E_WARNING, "SQLColAttribute can't handle SQL_DESC_OCTET_LENGTH: [%s] %s", state, errtxt);
1019					}
1020					 /* This is  a quirk for ODBC 2.0 compatibility for broken driver implementations.
1021					  */
1022					charextraalloc = 1;
1023					rc = SQLColAttributes(result->stmt, (SQLUSMALLINT)(i+1), SQL_COLUMN_DISPLAY_SIZE,
1024								NULL, 0, NULL, &displaysize);
1025				}
1026
1027				/* Workaround for drivers that report NVARCHAR(MAX) columns as SQL_WVARCHAR with size 0 (bug #69975) */
1028				if (result->values[i].coltype == SQL_WVARCHAR && displaysize == 0) {
1029					result->values[i].coltype = SQL_WLONGVARCHAR;
1030					result->values[i].value = NULL;
1031					break;
1032				}
1033#endif
1034				/* Workaround for Oracle ODBC Driver bug (#50162) when fetching TIMESTAMP column */
1035				if (result->values[i].coltype == SQL_TIMESTAMP) {
1036					displaysize += 3;
1037				}
1038
1039				if (charextraalloc) {
1040					/* Since we don't know the exact # of bytes, allocate extra */
1041					displaysize *= 4;
1042				}
1043				result->values[i].value = (char *)emalloc(displaysize + 1);
1044				rc = SQLBindCol(result->stmt, (SQLUSMALLINT)(i+1), SQL_C_CHAR, result->values[i].value,
1045							displaysize + 1, &result->values[i].vallen);
1046				break;
1047		}
1048	}
1049	return 1;
1050}
1051/* }}} */
1052
1053/* {{{ odbc_transact */
1054void odbc_transact(INTERNAL_FUNCTION_PARAMETERS, int type)
1055{
1056	odbc_connection *conn;
1057	RETCODE rc;
1058	zval *pv_conn;
1059
1060	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_conn) == FAILURE) {
1061		return;
1062	}
1063
1064	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
1065		RETURN_FALSE;
1066	}
1067
1068	rc = SQLTransact(conn->henv, conn->hdbc, (SQLUSMALLINT)((type)?SQL_COMMIT:SQL_ROLLBACK));
1069	if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
1070		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLTransact");
1071		RETURN_FALSE;
1072	}
1073
1074	RETURN_TRUE;
1075}
1076/* }}} */
1077
1078/* {{{ _close_pconn_with_res */
1079static int _close_pconn_with_res(zend_resource *le, zend_resource *res)
1080{
1081	if (le->type == le_pconn && (((odbc_connection *)(le->ptr))->res == res)){
1082		return 1;
1083	}else{
1084		return 0;
1085	}
1086}
1087/* }}} */
1088
1089/* {{{ odbc_column_lengths */
1090void odbc_column_lengths(INTERNAL_FUNCTION_PARAMETERS, int type)
1091{
1092	odbc_result *result;
1093#if defined(HAVE_SOLID) || defined(HAVE_SOLID_30)
1094	/* this seems to be necessary for Solid2.3 ( tested by
1095	 * tammy@synchronis.com) and Solid 3.0 (tested by eric@terra.telemediair.nl)
1096	 * Solid does not seem to declare a SQLINTEGER, but it does declare a
1097	 * SQL_INTEGER which does not work (despite being the same type as a SDWORD.
1098	 * Solid 3.5 does not have this issue.
1099	 */
1100	SDWORD len;
1101#else
1102	SQLLEN len;
1103#endif
1104	zval *pv_res;
1105	zend_long pv_num;
1106
1107	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &pv_res, &pv_num) == FAILURE) {
1108		return;
1109	}
1110
1111	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
1112		RETURN_FALSE;
1113	}
1114
1115	if (result->numcols == 0) {
1116		php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
1117		RETURN_FALSE;
1118	}
1119
1120	if (pv_num > result->numcols) {
1121		php_error_docref(NULL, E_WARNING, "Field index larger than number of fields");
1122		RETURN_FALSE;
1123	}
1124
1125	if (pv_num < 1) {
1126		php_error_docref(NULL, E_WARNING, "Field numbering starts at 1");
1127		RETURN_FALSE;
1128	}
1129
1130	PHP_ODBC_SQLCOLATTRIBUTE(result->stmt, (SQLUSMALLINT)pv_num, (SQLUSMALLINT) (type?SQL_COLUMN_SCALE:SQL_COLUMN_PRECISION), NULL, 0, NULL, &len);
1131
1132	RETURN_LONG(len);
1133}
1134/* }}} */
1135
1136/* Main User Functions */
1137
1138/* {{{ proto void odbc_close_all(void)
1139   Close all ODBC connections */
1140PHP_FUNCTION(odbc_close_all)
1141{
1142	zend_resource *p;
1143
1144	if (zend_parse_parameters_none() == FAILURE) {
1145		return;
1146	}
1147
1148	/* Loop through list and close all statements */
1149	ZEND_HASH_FOREACH_PTR(&EG(regular_list), p) {
1150		if (p->ptr && (p->type == le_result)) {
1151			zend_list_close(p);
1152		}
1153	} ZEND_HASH_FOREACH_END();
1154
1155	/* Second loop through list, now close all connections */
1156	ZEND_HASH_FOREACH_PTR(&EG(regular_list), p) {
1157		if (p->ptr) {
1158			if (p->type == le_conn){
1159				zend_list_close(p);
1160			} else if (p->type == le_pconn){
1161				zend_list_close(p);
1162				/* Delete the persistent connection */
1163				zend_hash_apply_with_argument(&EG(persistent_list),
1164					(apply_func_arg_t) _close_pconn_with_res, (void *)p);
1165			}
1166		}
1167	} ZEND_HASH_FOREACH_END();
1168}
1169/* }}} */
1170
1171/* {{{ proto bool odbc_binmode(int result_id, int mode)
1172   Handle binary column data */
1173PHP_FUNCTION(odbc_binmode)
1174{
1175	php_odbc_fetch_attribs(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
1176}
1177/* }}} */
1178
1179/* {{{ proto bool odbc_longreadlen(int result_id, int length)
1180   Handle LONG columns */
1181PHP_FUNCTION(odbc_longreadlen)
1182{
1183	php_odbc_fetch_attribs(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
1184}
1185/* }}} */
1186
1187/* {{{ proto resource odbc_prepare(resource connection_id, string query)
1188   Prepares a statement for execution */
1189PHP_FUNCTION(odbc_prepare)
1190{
1191	zval *pv_conn;
1192	char *query;
1193	size_t query_len;
1194	odbc_result *result = NULL;
1195	odbc_connection *conn;
1196	RETCODE rc;
1197	int i;
1198#ifdef HAVE_SQL_EXTENDED_FETCH
1199	SQLUINTEGER      scrollopts;
1200#endif
1201
1202	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &pv_conn, &query, &query_len) == FAILURE) {
1203		return;
1204	}
1205
1206	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
1207		RETURN_FALSE;
1208	}
1209
1210	result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
1211
1212	result->numparams = 0;
1213	result->param_info = NULL;
1214
1215	rc = PHP_ODBC_SQLALLOCSTMT(conn->hdbc, &(result->stmt));
1216	if (rc == SQL_INVALID_HANDLE) {
1217		efree(result);
1218		php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
1219		RETURN_FALSE;
1220	}
1221
1222	if (rc == SQL_ERROR) {
1223		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
1224		efree(result);
1225		RETURN_FALSE;
1226	}
1227
1228#ifdef HAVE_SQL_EXTENDED_FETCH
1229	/* Solid doesn't have ExtendedFetch, if DriverManager is used, get Info,
1230	   whether Driver supports ExtendedFetch */
1231	rc = SQLGetInfo(conn->hdbc, SQL_FETCH_DIRECTION, (void *) &scrollopts, sizeof(scrollopts), NULL);
1232	if (rc == SQL_SUCCESS) {
1233		if ((result->fetch_abs = (scrollopts & SQL_FD_FETCH_ABSOLUTE))) {
1234			/* Try to set CURSOR_TYPE to dynamic. Driver will replace this with other
1235			   type if not possible.
1236			*/
1237			SQLSetStmtOption(result->stmt, SQL_CURSOR_TYPE, ODBCG(default_cursortype));
1238		}
1239	} else {
1240		result->fetch_abs = 0;
1241	}
1242#endif
1243
1244	rc = SQLPrepare(result->stmt, query, SQL_NTS);
1245	switch (rc) {
1246		case SQL_SUCCESS:
1247			break;
1248		case SQL_SUCCESS_WITH_INFO:
1249			odbc_sql_error(conn, result->stmt, "SQLPrepare");
1250			break;
1251		default:
1252			odbc_sql_error(conn, result->stmt, "SQLPrepare");
1253			RETURN_FALSE;
1254	}
1255
1256	SQLNumParams(result->stmt, &(result->numparams));
1257	SQLNumResultCols(result->stmt, &(result->numcols));
1258
1259	if (result->numcols > 0) {
1260		if (!odbc_bindcols(result)) {
1261			efree(result);
1262			RETURN_FALSE;
1263		}
1264	} else {
1265		result->values = NULL;
1266	}
1267	Z_ADDREF_P(pv_conn);
1268	result->conn_ptr = conn;
1269	result->fetched = 0;
1270
1271	result->param_info = (odbc_param_info *) safe_emalloc(sizeof(odbc_param_info), result->numparams, 0);
1272	for (i=0;i<result->numparams;i++) {
1273		rc = SQLDescribeParam(result->stmt, (SQLUSMALLINT)(i+1), &result->param_info[i].sqltype, &result->param_info[i].precision,
1274													&result->param_info[i].scale, &result->param_info[i].nullable);
1275		if (rc == SQL_ERROR) {
1276			odbc_sql_error(result->conn_ptr, result->stmt, "SQLDescribeParameter");
1277			SQLFreeStmt(result->stmt, SQL_RESET_PARAMS);
1278			efree(result->param_info);
1279			efree(result);
1280			RETURN_FALSE;
1281		}
1282	}
1283
1284	RETURN_RES(zend_register_resource(result, le_result));
1285}
1286/* }}} */
1287
1288/*
1289 * Execute prepared SQL statement. Supports only input parameters.
1290 */
1291
1292/* {{{ proto bool odbc_execute(resource result_id [, array parameters_array])
1293   Execute a prepared statement */
1294PHP_FUNCTION(odbc_execute)
1295{
1296	zval *pv_res, *pv_param_arr, *tmp;
1297	typedef struct params_t {
1298		SQLLEN vallen;
1299		int fp;
1300	} params_t;
1301	params_t *params = NULL;
1302	char *filename;
1303	unsigned char otype;
1304	SQLSMALLINT ctype;
1305   	odbc_result *result;
1306	int numArgs, i, ne;
1307	RETCODE rc;
1308
1309	numArgs = ZEND_NUM_ARGS();
1310
1311	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|a", &pv_res, &pv_param_arr) == FAILURE) {
1312		return;
1313	}
1314
1315	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
1316		RETURN_FALSE;
1317	}
1318
1319	/* XXX check for already bound parameters*/
1320	if (result->numparams > 0 && numArgs == 1) {
1321		php_error_docref(NULL, E_WARNING, "No parameters to SQL statement given");
1322		RETURN_FALSE;
1323	}
1324
1325	if (result->numparams > 0) {
1326		if ((ne = zend_hash_num_elements(Z_ARRVAL_P(pv_param_arr))) < result->numparams) {
1327			php_error_docref(NULL, E_WARNING,"Not enough parameters (%d should be %d) given", ne, result->numparams);
1328			RETURN_FALSE;
1329		}
1330
1331		zend_hash_internal_pointer_reset(Z_ARRVAL_P(pv_param_arr));
1332		params = (params_t *)safe_emalloc(sizeof(params_t), result->numparams, 0);
1333		for(i = 0; i < result->numparams; i++) {
1334			params[i].fp = -1;
1335		}
1336
1337		for(i = 1; i <= result->numparams; i++) {
1338			if ((tmp = zend_hash_get_current_data(Z_ARRVAL_P(pv_param_arr))) == NULL) {
1339				php_error_docref(NULL, E_WARNING,"Error getting parameter");
1340				SQLFreeStmt(result->stmt,SQL_RESET_PARAMS);
1341				for (i = 0; i < result->numparams; i++) {
1342					if (params[i].fp != -1) {
1343						close(params[i].fp);
1344					}
1345				}
1346				efree(params);
1347				RETURN_FALSE;
1348			}
1349
1350			otype = Z_TYPE_P(tmp);
1351			convert_to_string_ex(tmp);
1352			if (Z_TYPE_P(tmp) != IS_STRING) {
1353				php_error_docref(NULL, E_WARNING,"Error converting parameter");
1354				SQLFreeStmt(result->stmt, SQL_RESET_PARAMS);
1355				for (i = 0; i < result->numparams; i++) {
1356					if (params[i].fp != -1) {
1357						close(params[i].fp);
1358					}
1359				}
1360				efree(params);
1361				RETURN_FALSE;
1362			}
1363
1364			params[i-1].vallen = Z_STRLEN_P(tmp);
1365			params[i-1].fp = -1;
1366
1367			if (IS_SQL_BINARY(result->param_info[i-1].sqltype)) {
1368				ctype = SQL_C_BINARY;
1369			} else {
1370				ctype = SQL_C_CHAR;
1371			}
1372
1373			if (Z_STRLEN_P(tmp) > 2 &&
1374				Z_STRVAL_P(tmp)[0] == '\'' &&
1375				Z_STRVAL_P(tmp)[Z_STRLEN_P(tmp) - 1] == '\'') {
1376
1377				if (CHECK_ZVAL_NULL_PATH(tmp)) {
1378					RETURN_FALSE;
1379				}
1380				filename = estrndup(&Z_STRVAL_P(tmp)[1], Z_STRLEN_P(tmp) - 2);
1381				filename[strlen(filename)] = '\0';
1382
1383				/* Check the basedir */
1384				if (php_check_open_basedir(filename)) {
1385					efree(filename);
1386					SQLFreeStmt(result->stmt, SQL_RESET_PARAMS);
1387					for (i = 0; i < result->numparams; i++) {
1388						if (params[i].fp != -1) {
1389							close(params[i].fp);
1390						}
1391					}
1392					efree(params);
1393					RETURN_FALSE;
1394				}
1395
1396				if ((params[i-1].fp = open(filename,O_RDONLY)) == -1) {
1397					php_error_docref(NULL, E_WARNING,"Can't open file %s", filename);
1398					SQLFreeStmt(result->stmt, SQL_RESET_PARAMS);
1399					for (i = 0; i < result->numparams; i++) {
1400						if (params[i].fp != -1) {
1401							close(params[i].fp);
1402						}
1403					}
1404					efree(params);
1405					efree(filename);
1406					RETURN_FALSE;
1407				}
1408
1409				efree(filename);
1410
1411				params[i-1].vallen = SQL_LEN_DATA_AT_EXEC(0);
1412
1413				rc = SQLBindParameter(result->stmt, (SQLUSMALLINT)i, SQL_PARAM_INPUT,
1414									  ctype, result->param_info[i-1].sqltype, result->param_info[i-1].precision, result->param_info[i-1].scale,
1415									  (void *)(intptr_t)params[i-1].fp, 0,
1416									  &params[i-1].vallen);
1417			} else {
1418#ifdef HAVE_DBMAKER
1419				precision = params[i-1].vallen;
1420#endif
1421				if (otype == IS_NULL) {
1422					params[i-1].vallen = SQL_NULL_DATA;
1423				}
1424
1425				rc = SQLBindParameter(result->stmt, (SQLUSMALLINT)i, SQL_PARAM_INPUT,
1426									  ctype, result->param_info[i-1].sqltype, result->param_info[i-1].precision, result->param_info[i-1].scale,
1427									  Z_STRVAL_P(tmp), 0,
1428									  &params[i-1].vallen);
1429			}
1430			if (rc == SQL_ERROR) {
1431				odbc_sql_error(result->conn_ptr, result->stmt, "SQLBindParameter");
1432				SQLFreeStmt(result->stmt, SQL_RESET_PARAMS);
1433				for (i = 0; i < result->numparams; i++) {
1434					if (params[i].fp != -1) {
1435						close(params[i].fp);
1436					}
1437				}
1438				efree(params);
1439				RETURN_FALSE;
1440			}
1441			zend_hash_move_forward(Z_ARRVAL_P(pv_param_arr));
1442		}
1443	}
1444	/* Close cursor, needed for doing multiple selects */
1445	rc = SQLFreeStmt(result->stmt, SQL_CLOSE);
1446
1447	if (rc == SQL_ERROR) {
1448		odbc_sql_error(result->conn_ptr, result->stmt, "SQLFreeStmt");
1449	}
1450
1451	rc = SQLExecute(result->stmt);
1452
1453	result->fetched = 0;
1454	if (rc == SQL_NEED_DATA) {
1455		char buf[4096];
1456		int fp, nbytes;
1457		while (rc == SQL_NEED_DATA) {
1458			rc = SQLParamData(result->stmt, (void*)&fp);
1459			if (rc == SQL_NEED_DATA) {
1460				while ((nbytes = read(fp, &buf, 4096)) > 0) {
1461					SQLPutData(result->stmt, (void*)&buf, nbytes);
1462				}
1463			}
1464		}
1465	} else {
1466		switch (rc) {
1467			case SQL_SUCCESS:
1468				break;
1469			case SQL_NO_DATA_FOUND:
1470			case SQL_SUCCESS_WITH_INFO:
1471				odbc_sql_error(result->conn_ptr, result->stmt, "SQLExecute");
1472				break;
1473			default:
1474				odbc_sql_error(result->conn_ptr, result->stmt, "SQLExecute");
1475				RETVAL_FALSE;
1476		}
1477	}
1478
1479	if (result->numparams > 0) {
1480		SQLFreeStmt(result->stmt, SQL_RESET_PARAMS);
1481		for(i = 0; i < result->numparams; i++) {
1482			if (params[i].fp != -1) {
1483				close(params[i].fp);
1484			}
1485		}
1486		efree(params);
1487	}
1488
1489	if (rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO || rc == SQL_NO_DATA_FOUND) {
1490		RETVAL_TRUE;
1491	}
1492
1493	if (result->numcols == 0) {
1494		SQLNumResultCols(result->stmt, &(result->numcols));
1495
1496		if (result->numcols > 0) {
1497			if (!odbc_bindcols(result)) {
1498				efree(result);
1499				RETVAL_FALSE;
1500			}
1501		} else {
1502			result->values = NULL;
1503		}
1504	}
1505}
1506/* }}} */
1507
1508/* {{{ proto string odbc_cursor(resource result_id)
1509   Get cursor name */
1510PHP_FUNCTION(odbc_cursor)
1511{
1512	zval *pv_res;
1513	SQLUSMALLINT max_len;
1514	SQLSMALLINT len;
1515	char *cursorname;
1516   	odbc_result *result;
1517	RETCODE rc;
1518
1519	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_res) == FAILURE) {
1520		return;
1521	}
1522
1523	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
1524		RETURN_FALSE;
1525	}
1526
1527	rc = SQLGetInfo(result->conn_ptr->hdbc,SQL_MAX_CURSOR_NAME_LEN, (void *)&max_len,sizeof(max_len),&len);
1528	if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
1529		RETURN_FALSE;
1530	}
1531
1532	if (max_len > 0) {
1533		cursorname = emalloc(max_len + 1);
1534		rc = SQLGetCursorName(result->stmt,cursorname,(SQLSMALLINT)max_len,&len);
1535		if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
1536			char        state[6];     /* Not used */
1537	 		SQLINTEGER  error;        /* Not used */
1538			char        errormsg[SQL_MAX_MESSAGE_LENGTH];
1539			SQLSMALLINT errormsgsize; /* Not used */
1540
1541			SQLError( result->conn_ptr->henv, result->conn_ptr->hdbc,
1542						result->stmt, state, &error, errormsg,
1543						sizeof(errormsg)-1, &errormsgsize);
1544			if (!strncmp(state,"S1015",5)) {
1545				snprintf(cursorname, max_len+1, "php_curs_" ZEND_ULONG_FMT, (zend_ulong)result->stmt);
1546				if (SQLSetCursorName(result->stmt,cursorname,SQL_NTS) != SQL_SUCCESS) {
1547					odbc_sql_error(result->conn_ptr, result->stmt, "SQLSetCursorName");
1548					RETVAL_FALSE;
1549				} else {
1550					RETVAL_STRING(cursorname);
1551				}
1552			} else {
1553				php_error_docref(NULL, E_WARNING, "SQL error: %s, SQL state %s", errormsg, state);
1554				RETVAL_FALSE;
1555			}
1556		} else {
1557			RETVAL_STRING(cursorname);
1558		}
1559		efree(cursorname);
1560	} else {
1561		RETVAL_FALSE;
1562	}
1563}
1564/* }}} */
1565
1566#ifdef HAVE_SQLDATASOURCES
1567/* {{{ proto array odbc_data_source(resource connection_id, int fetch_type)
1568   Return information about the currently connected data source */
1569PHP_FUNCTION(odbc_data_source)
1570{
1571	zval *zv_conn;
1572	zend_long zv_fetch_type;
1573	RETCODE rc = 0; /* assume all is good */
1574	odbc_connection *conn;
1575	UCHAR server_name[100], desc[200];
1576	SQLSMALLINT len1=0, len2=0, fetch_type;
1577
1578	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &zv_conn, &zv_fetch_type) == FAILURE) {
1579		return;
1580	}
1581
1582	fetch_type = (SQLSMALLINT) zv_fetch_type;
1583
1584	if (!(fetch_type == SQL_FETCH_FIRST || fetch_type == SQL_FETCH_NEXT)) {
1585		php_error_docref(NULL, E_WARNING, "Invalid fetch type (%d)", fetch_type);
1586		RETURN_FALSE;
1587	}
1588
1589	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(zv_conn), "ODBC-Link", le_conn, le_pconn))) {
1590		RETURN_FALSE;
1591	}
1592
1593	/* now we have the "connection" lets call the DataSource object */
1594	rc = SQLDataSources(conn->henv,
1595			fetch_type,
1596			server_name,
1597			(SQLSMALLINT)sizeof(server_name),
1598			&len1,
1599			desc,
1600			(SQLSMALLINT)sizeof(desc),
1601			&len2);
1602
1603	if (rc != SQL_SUCCESS) {
1604		/* ummm.... he did it */
1605		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLDataSources");
1606		RETURN_FALSE;
1607	}
1608
1609	if (len1 == 0 || len2 == 0) {
1610		/* we have a non-valid entry... so stop the looping */
1611		RETURN_FALSE;
1612	}
1613
1614	array_init(return_value);
1615
1616	add_assoc_string_ex(return_value, "server", sizeof("server")-1, server_name);
1617	add_assoc_string_ex(return_value, "description", sizeof("description")-1, desc);
1618
1619}
1620/* }}} */
1621#endif /* HAVE_SQLDATASOURCES */
1622
1623/* {{{ proto resource odbc_exec(resource connection_id, string query [, int flags])
1624   Prepare and execute an SQL statement */
1625/* XXX Use flags */
1626PHP_FUNCTION(odbc_exec)
1627{
1628	zval *pv_conn;
1629	zend_long pv_flags;
1630	int numArgs;
1631	char *query;
1632	size_t query_len;
1633	odbc_result *result = NULL;
1634	odbc_connection *conn;
1635	RETCODE rc;
1636#ifdef HAVE_SQL_EXTENDED_FETCH
1637	SQLUINTEGER      scrollopts;
1638#endif
1639
1640	numArgs = ZEND_NUM_ARGS();
1641
1642	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs|l", &pv_conn, &query, &query_len, &pv_flags) == FAILURE) {
1643		return;
1644	}
1645
1646	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
1647		RETURN_FALSE;
1648	}
1649
1650	result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
1651
1652	rc = PHP_ODBC_SQLALLOCSTMT(conn->hdbc, &(result->stmt));
1653	if (rc == SQL_INVALID_HANDLE) {
1654		php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
1655		efree(result);
1656		RETURN_FALSE;
1657	}
1658
1659	if (rc == SQL_ERROR) {
1660		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
1661		efree(result);
1662		RETURN_FALSE;
1663	}
1664
1665#ifdef HAVE_SQL_EXTENDED_FETCH
1666	/* Solid doesn't have ExtendedFetch, if DriverManager is used, get Info,
1667	   whether Driver supports ExtendedFetch */
1668	rc = SQLGetInfo(conn->hdbc, SQL_FETCH_DIRECTION, (void *) &scrollopts, sizeof(scrollopts), NULL);
1669	if (rc == SQL_SUCCESS) {
1670		if ((result->fetch_abs = (scrollopts & SQL_FD_FETCH_ABSOLUTE))) {
1671			/* Try to set CURSOR_TYPE to dynamic. Driver will replace this with other
1672			   type if not possible.
1673			 */
1674			SQLSetStmtOption(result->stmt, SQL_CURSOR_TYPE, ODBCG(default_cursortype));
1675		}
1676	} else {
1677		result->fetch_abs = 0;
1678	}
1679#endif
1680
1681	rc = SQLExecDirect(result->stmt, query, SQL_NTS);
1682	if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO && rc != SQL_NO_DATA_FOUND) {
1683		/* XXX FIXME we should really check out SQLSTATE with SQLError
1684		 * in case rc is SQL_SUCCESS_WITH_INFO here.
1685		 */
1686		odbc_sql_error(conn, result->stmt, "SQLExecDirect");
1687		SQLFreeStmt(result->stmt, SQL_DROP);
1688		efree(result);
1689		RETURN_FALSE;
1690	}
1691
1692	SQLNumResultCols(result->stmt, &(result->numcols));
1693
1694	/* For insert, update etc. cols == 0 */
1695	if (result->numcols > 0) {
1696		if (!odbc_bindcols(result)) {
1697			efree(result);
1698			RETURN_FALSE;
1699		}
1700	} else {
1701		result->values = NULL;
1702	}
1703	Z_ADDREF_P(pv_conn);
1704	result->conn_ptr = conn;
1705	result->fetched = 0;
1706	RETURN_RES(zend_register_resource(result, le_result));
1707}
1708/* }}} */
1709
1710#ifdef PHP_ODBC_HAVE_FETCH_HASH
1711#define ODBC_NUM  1
1712#define ODBC_OBJECT  2
1713
1714/* {{{ php_odbc_fetch_hash */
1715static void php_odbc_fetch_hash(INTERNAL_FUNCTION_PARAMETERS, int result_type)
1716{
1717	int i;
1718	odbc_result *result;
1719	RETCODE rc;
1720	SQLSMALLINT sql_c_type;
1721	char *buf = NULL;
1722#ifdef HAVE_SQL_EXTENDED_FETCH
1723	SQLULEN crow;
1724	SQLUSMALLINT RowStatus[1];
1725	SQLLEN rownum;
1726	zval *pv_res, tmp;
1727	zend_long pv_row = -1;
1728
1729	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &pv_res, &pv_row) == FAILURE) {
1730		return;
1731	}
1732
1733	rownum = pv_row;
1734#else
1735	zval *pv_res, tmp;
1736
1737	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_res) == FAILURE) {
1738		return;
1739	}
1740#endif
1741
1742	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
1743		RETURN_FALSE;
1744	}
1745
1746	if (result->numcols == 0) {
1747		php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
1748		RETURN_FALSE;
1749	}
1750
1751#ifdef HAVE_SQL_EXTENDED_FETCH
1752	if (result->fetch_abs) {
1753		if (rownum > 0) {
1754			rc = SQLExtendedFetch(result->stmt,SQL_FETCH_ABSOLUTE,rownum,&crow,RowStatus);
1755		} else {
1756			rc = SQLExtendedFetch(result->stmt,SQL_FETCH_NEXT,1,&crow,RowStatus);
1757		}
1758	} else
1759#endif
1760	rc = SQLFetch(result->stmt);
1761
1762	if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
1763		RETURN_FALSE;
1764	}
1765
1766	array_init(return_value);
1767
1768#ifdef HAVE_SQL_EXTENDED_FETCH
1769	if (rownum > 0 && result->fetch_abs)
1770		result->fetched = rownum;
1771	else
1772#endif
1773		result->fetched++;
1774
1775	for(i = 0; i < result->numcols; i++) {
1776		sql_c_type = SQL_C_CHAR;
1777
1778		switch(result->values[i].coltype) {
1779			case SQL_BINARY:
1780			case SQL_VARBINARY:
1781			case SQL_LONGVARBINARY:
1782				if (result->binmode <= 0) {
1783					ZVAL_EMPTY_STRING(&tmp);
1784					break;
1785				}
1786				if (result->binmode == 1) {
1787					sql_c_type = SQL_C_BINARY;
1788				}
1789			case SQL_LONGVARCHAR:
1790#if defined(ODBCVER) && (ODBCVER >= 0x0300)
1791			case SQL_WLONGVARCHAR:
1792#endif
1793				if (IS_SQL_LONG(result->values[i].coltype) && result->longreadlen <= 0) {
1794					ZVAL_EMPTY_STRING(&tmp);
1795					break;
1796				}
1797				if (buf == NULL) {
1798					buf = emalloc(result->longreadlen + 1);
1799				}
1800
1801				rc = SQLGetData(result->stmt, (SQLUSMALLINT)(i + 1), sql_c_type, buf, result->longreadlen + 1, &result->values[i].vallen);
1802
1803				if (rc == SQL_ERROR) {
1804					odbc_sql_error(result->conn_ptr, result->stmt, "SQLGetData");
1805					efree(buf);
1806					RETURN_FALSE;
1807				}
1808
1809				if (rc == SQL_SUCCESS_WITH_INFO) {
1810					ZVAL_STRINGL(&tmp, buf, result->longreadlen);
1811				} else if (result->values[i].vallen == SQL_NULL_DATA) {
1812					ZVAL_NULL(&tmp);
1813					break;
1814				} else {
1815					ZVAL_STRINGL(&tmp, buf, result->values[i].vallen);
1816				}
1817				break;
1818
1819			default:
1820				if (result->values[i].vallen == SQL_NULL_DATA) {
1821					ZVAL_NULL(&tmp);
1822					break;
1823				}
1824				ZVAL_STRINGL(&tmp, result->values[i].value, result->values[i].vallen);
1825				break;
1826		}
1827
1828		if (result_type & ODBC_NUM) {
1829			zend_hash_index_update(Z_ARRVAL_P(return_value), i, &tmp);
1830		} else {
1831			if (!*(result->values[i].name) && Z_TYPE(tmp) == IS_STRING) {
1832				zend_hash_update(Z_ARRVAL_P(return_value), Z_STR(tmp), &tmp);
1833			} else {
1834				zend_hash_str_update(Z_ARRVAL_P(return_value), result->values[i].name, strlen(result->values[i].name), &tmp);
1835			}
1836		}
1837	}
1838	if (buf) {
1839		efree(buf);
1840	}
1841}
1842/* }}} */
1843
1844
1845/* {{{ proto object odbc_fetch_object(int result [, int rownumber])
1846   Fetch a result row as an object */
1847PHP_FUNCTION(odbc_fetch_object)
1848{
1849	php_odbc_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, ODBC_OBJECT);
1850	if (Z_TYPE_P(return_value) == IS_ARRAY) {
1851		object_and_properties_init(return_value, ZEND_STANDARD_CLASS_DEF_PTR, Z_ARRVAL_P(return_value));
1852	}
1853}
1854/* }}} */
1855
1856/* {{{ proto array odbc_fetch_array(int result [, int rownumber])
1857   Fetch a result row as an associative array */
1858PHP_FUNCTION(odbc_fetch_array)
1859{
1860	php_odbc_fetch_hash(INTERNAL_FUNCTION_PARAM_PASSTHRU, ODBC_OBJECT);
1861}
1862/* }}} */
1863#endif
1864
1865/* {{{ proto int odbc_fetch_into(resource result_id, array &result_array [, int rownumber])
1866   Fetch one result row into an array */
1867PHP_FUNCTION(odbc_fetch_into)
1868{
1869	int i;
1870	odbc_result *result;
1871	RETCODE rc;
1872	SQLSMALLINT sql_c_type;
1873	char *buf = NULL;
1874	zval *pv_res, *pv_res_arr, tmp;
1875#ifdef HAVE_SQL_EXTENDED_FETCH
1876	zend_long pv_row = 0;
1877	SQLULEN crow;
1878	SQLUSMALLINT RowStatus[1];
1879	SQLLEN rownum = -1;
1880#endif /* HAVE_SQL_EXTENDED_FETCH */
1881
1882#ifdef HAVE_SQL_EXTENDED_FETCH
1883	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rz/|l", &pv_res, &pv_res_arr, &pv_row) == FAILURE) {
1884		return;
1885	}
1886
1887	rownum = pv_row;
1888#else
1889	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rz/", &pv_res, &pv_res_arr) == FAILURE) {
1890		return;
1891	}
1892#endif /* HAVE_SQL_EXTENDED_FETCH */
1893
1894	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
1895		RETURN_FALSE;
1896	}
1897
1898	if (result->numcols == 0) {
1899		php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
1900		RETURN_FALSE;
1901	}
1902
1903	if (Z_TYPE_P(pv_res_arr) != IS_ARRAY) {
1904		array_init(pv_res_arr);
1905	}
1906
1907#ifdef HAVE_SQL_EXTENDED_FETCH
1908	if (result->fetch_abs) {
1909		if (rownum > 0) {
1910			rc = SQLExtendedFetch(result->stmt,SQL_FETCH_ABSOLUTE,rownum,&crow,RowStatus);
1911		} else {
1912			rc = SQLExtendedFetch(result->stmt,SQL_FETCH_NEXT,1,&crow,RowStatus);
1913		}
1914	} else
1915#endif
1916		rc = SQLFetch(result->stmt);
1917
1918	if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
1919		RETURN_FALSE;
1920	}
1921
1922#ifdef HAVE_SQL_EXTENDED_FETCH
1923	if (rownum > 0 && result->fetch_abs)
1924		result->fetched = rownum;
1925	else
1926#endif
1927		result->fetched++;
1928
1929	for(i = 0; i < result->numcols; i++) {
1930		sql_c_type = SQL_C_CHAR;
1931
1932		switch(result->values[i].coltype) {
1933			case SQL_BINARY:
1934			case SQL_VARBINARY:
1935			case SQL_LONGVARBINARY:
1936				if (result->binmode <= 0) {
1937					ZVAL_EMPTY_STRING(&tmp);
1938					break;
1939				}
1940				if (result->binmode == 1) sql_c_type = SQL_C_BINARY;
1941
1942			case SQL_LONGVARCHAR:
1943#if defined(ODBCVER) && (ODBCVER >= 0x0300)
1944			case SQL_WLONGVARCHAR:
1945#endif
1946				if (IS_SQL_LONG(result->values[i].coltype) && result->longreadlen <= 0) {
1947					ZVAL_EMPTY_STRING(&tmp);
1948					break;
1949				}
1950
1951				if (buf == NULL) {
1952					buf = emalloc(result->longreadlen + 1);
1953				}
1954				rc = SQLGetData(result->stmt, (SQLUSMALLINT)(i + 1),sql_c_type, buf, result->longreadlen + 1, &result->values[i].vallen);
1955
1956				if (rc == SQL_ERROR) {
1957					odbc_sql_error(result->conn_ptr, result->stmt, "SQLGetData");
1958					efree(buf);
1959					RETURN_FALSE;
1960				}
1961				if (rc == SQL_SUCCESS_WITH_INFO) {
1962					ZVAL_STRINGL(&tmp, buf, result->longreadlen);
1963				} else if (result->values[i].vallen == SQL_NULL_DATA) {
1964					ZVAL_NULL(&tmp);
1965					break;
1966				} else {
1967					ZVAL_STRINGL(&tmp, buf, result->values[i].vallen);
1968				}
1969				break;
1970
1971			default:
1972				if (result->values[i].vallen == SQL_NULL_DATA) {
1973					ZVAL_NULL(&tmp);
1974					break;
1975				}
1976				ZVAL_STRINGL(&tmp, result->values[i].value, result->values[i].vallen);
1977				break;
1978		}
1979		zend_hash_index_update(Z_ARRVAL_P(pv_res_arr), i, &tmp);
1980	}
1981	if (buf) efree(buf);
1982	RETURN_LONG(result->numcols);
1983}
1984/* }}} */
1985
1986/* {{{ proto bool solid_fetch_prev(resource result_id)
1987   */
1988#if defined(HAVE_SOLID) || defined(HAVE_SOLID_30) || defined(HAVE_SOLID_35)
1989PHP_FUNCTION(solid_fetch_prev)
1990{
1991	odbc_result *result;
1992	RETCODE rc;
1993	zval *pv_res;
1994
1995	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_res) == FAILURE) {
1996		return;
1997	}
1998
1999	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2000		RETURN_FALSE;
2001	}
2002	if (result->numcols == 0) {
2003		php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
2004		RETURN_FALSE;
2005	}
2006	rc = SQLFetchPrev(result->stmt);
2007
2008	if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
2009		RETURN_FALSE;
2010	}
2011
2012	if (result->fetched > 1) {
2013		result->fetched--;
2014	}
2015
2016	RETURN_TRUE;
2017}
2018#endif
2019/* }}} */
2020
2021/* {{{ proto bool odbc_fetch_row(resource result_id [, int row_number])
2022   Fetch a row */
2023PHP_FUNCTION(odbc_fetch_row)
2024{
2025	SQLLEN rownum;
2026	odbc_result *result;
2027	RETCODE rc;
2028	zval *pv_res;
2029	zend_long pv_row = 1;
2030#ifdef HAVE_SQL_EXTENDED_FETCH
2031	SQLULEN crow;
2032	SQLUSMALLINT RowStatus[1];
2033#endif
2034
2035	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &pv_res, &pv_row) == FAILURE) {
2036		return;
2037	}
2038
2039	rownum = pv_row;
2040
2041	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2042		RETURN_FALSE;
2043	}
2044
2045	if (result->numcols == 0) {
2046		php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
2047		RETURN_FALSE;
2048	}
2049
2050#ifdef HAVE_SQL_EXTENDED_FETCH
2051	if (result->fetch_abs) {
2052		if (ZEND_NUM_ARGS() > 1) {
2053			rc = SQLExtendedFetch(result->stmt,SQL_FETCH_ABSOLUTE,rownum,&crow,RowStatus);
2054		} else {
2055			rc = SQLExtendedFetch(result->stmt,SQL_FETCH_NEXT,1,&crow,RowStatus);
2056		}
2057	} else
2058#endif
2059		rc = SQLFetch(result->stmt);
2060
2061	if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
2062		RETURN_FALSE;
2063	}
2064
2065	if (ZEND_NUM_ARGS() > 1) {
2066		result->fetched = rownum;
2067	} else {
2068		result->fetched++;
2069	}
2070
2071	RETURN_TRUE;
2072}
2073/* }}} */
2074
2075/* {{{ proto mixed odbc_result(resource result_id, mixed field)
2076   Get result data */
2077PHP_FUNCTION(odbc_result)
2078{
2079	char *field;
2080	zend_string *field_str;
2081	int field_ind;
2082	SQLSMALLINT sql_c_type = SQL_C_CHAR;
2083	odbc_result *result;
2084	int i = 0;
2085	RETCODE rc;
2086	SQLLEN	fieldsize;
2087	zval *pv_res, *pv_field;
2088#ifdef HAVE_SQL_EXTENDED_FETCH
2089	SQLULEN crow;
2090	SQLUSMALLINT RowStatus[1];
2091#endif
2092
2093	field_ind = -1;
2094	field = NULL;
2095
2096	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rz", &pv_res, &pv_field) == FAILURE) {
2097		return;
2098	}
2099
2100	if (Z_TYPE_P(pv_field) == IS_STRING) {
2101		field = Z_STRVAL_P(pv_field);
2102	} else {
2103		convert_to_long_ex(pv_field);
2104		field_ind = Z_LVAL_P(pv_field) - 1;
2105	}
2106
2107	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2108		RETURN_FALSE;
2109	}
2110
2111	if ((result->numcols == 0)) {
2112		php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
2113		RETURN_FALSE;
2114	}
2115
2116	/* get field index if the field parameter was a string */
2117	if (field != NULL) {
2118		if (result->values == NULL) {
2119			php_error_docref(NULL, E_WARNING, "Result set contains no data");
2120			RETURN_FALSE;
2121		}
2122
2123		for(i = 0; i < result->numcols; i++) {
2124			if (!strcasecmp(result->values[i].name, field)) {
2125				field_ind = i;
2126				break;
2127			}
2128		}
2129
2130		if (field_ind < 0) {
2131			php_error_docref(NULL, E_WARNING, "Field %s not found", field);
2132			RETURN_FALSE;
2133		}
2134	} else {
2135		/* check for limits of field_ind if the field parameter was an int */
2136		if (field_ind >= result->numcols || field_ind < 0) {
2137			php_error_docref(NULL, E_WARNING, "Field index is larger than the number of fields");
2138			RETURN_FALSE;
2139		}
2140	}
2141
2142	if (result->fetched == 0) {
2143		/* User forgot to call odbc_fetch_row(), or wants to reload the results, do it now */
2144#ifdef HAVE_SQL_EXTENDED_FETCH
2145		if (result->fetch_abs)
2146			rc = SQLExtendedFetch(result->stmt, SQL_FETCH_NEXT, 1, &crow,RowStatus);
2147		else
2148#endif
2149			rc = SQLFetch(result->stmt);
2150
2151		if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
2152			RETURN_FALSE;
2153		}
2154
2155		result->fetched++;
2156	}
2157
2158	switch(result->values[field_ind].coltype) {
2159		case SQL_BINARY:
2160		case SQL_VARBINARY:
2161		case SQL_LONGVARBINARY:
2162			if (result->binmode <= 1) {
2163				sql_c_type = SQL_C_BINARY;
2164			}
2165			if (result->binmode <= 0) {
2166				break;
2167			}
2168		case SQL_LONGVARCHAR:
2169#if defined(ODBCVER) && (ODBCVER >= 0x0300)
2170		case SQL_WLONGVARCHAR:
2171#endif
2172			if (IS_SQL_LONG(result->values[field_ind].coltype)) {
2173				if (result->longreadlen <= 0) {
2174				   break;
2175				} else {
2176				   fieldsize = result->longreadlen;
2177				}
2178			} else {
2179			   PHP_ODBC_SQLCOLATTRIBUTE(result->stmt, (SQLUSMALLINT)(field_ind + 1),
2180					   			(SQLUSMALLINT)((sql_c_type == SQL_C_BINARY) ? SQL_COLUMN_LENGTH :
2181					   			SQL_COLUMN_DISPLAY_SIZE),
2182					   			NULL, 0, NULL, &fieldsize);
2183			}
2184			/* For char data, the length of the returned string will be longreadlen - 1 */
2185			fieldsize = (result->longreadlen <= 0) ? 4096 : result->longreadlen;
2186			field_str = zend_string_alloc(fieldsize, 0);
2187
2188		/* SQLGetData will truncate CHAR data to fieldsize - 1 bytes and append \0.
2189		 * For binary data it is truncated to fieldsize bytes.
2190		 */
2191			rc = SQLGetData(result->stmt, (SQLUSMALLINT)(field_ind + 1), sql_c_type,
2192							ZSTR_VAL(field_str), fieldsize, &result->values[field_ind].vallen);
2193
2194			if (rc == SQL_ERROR) {
2195				odbc_sql_error(result->conn_ptr, result->stmt, "SQLGetData");
2196				zend_string_free(field_str);
2197				RETURN_FALSE;
2198			}
2199
2200			if (result->values[field_ind].vallen == SQL_NULL_DATA) {
2201				zend_string_free(field_str);
2202				RETURN_NULL();
2203			} else if (rc == SQL_NO_DATA_FOUND) {
2204				zend_string_free(field_str);
2205				RETURN_FALSE;
2206			}
2207			/* Reduce fieldlen by 1 if we have char data. One day we might
2208			   have binary strings... */
2209			if ((result->values[field_ind].coltype == SQL_LONGVARCHAR)
2210#if defined(ODBCVER) && (ODBCVER >= 0x0300)
2211			    || (result->values[field_ind].coltype == SQL_WLONGVARCHAR)
2212#endif
2213			) {
2214				fieldsize -= 1;
2215			}
2216			/* Don't duplicate result, saves one emalloc.
2217			   For SQL_SUCCESS, the length is in vallen.
2218			 */
2219			if (rc != SQL_SUCCESS_WITH_INFO) {
2220				field_str = zend_string_truncate(field_str, result->values[field_ind].vallen, 0);
2221			}
2222			RETURN_NEW_STR(field_str);
2223			break;
2224
2225		default:
2226			if (result->values[field_ind].vallen == SQL_NULL_DATA) {
2227				RETURN_NULL();
2228			} else {
2229				RETURN_STRINGL(result->values[field_ind].value, result->values[field_ind].vallen);
2230			}
2231			break;
2232	}
2233
2234/* If we come here, output unbound LONG and/or BINARY column data to the client */
2235
2236	/* We emalloc 1 byte more for SQL_C_CHAR (trailing \0) */
2237	fieldsize = (sql_c_type == SQL_C_CHAR) ? 4096 : 4095;
2238	field = emalloc(fieldsize);
2239
2240	/* Call SQLGetData() until SQL_SUCCESS is returned */
2241	while(1) {
2242		rc = SQLGetData(result->stmt, (SQLUSMALLINT)(field_ind + 1),sql_c_type, field, fieldsize, &result->values[field_ind].vallen);
2243
2244		if (rc == SQL_ERROR) {
2245			odbc_sql_error(result->conn_ptr, result->stmt, "SQLGetData");
2246			efree(field);
2247			RETURN_FALSE;
2248		}
2249
2250		if (result->values[field_ind].vallen == SQL_NULL_DATA) {
2251			efree(field);
2252			RETURN_NULL();
2253		}
2254		/* chop the trailing \0 by outputing only 4095 bytes */
2255		PHPWRITE(field,(rc == SQL_SUCCESS_WITH_INFO) ? 4095 : result->values[field_ind].vallen);
2256
2257		if (rc == SQL_SUCCESS) { /* no more data avail */
2258			efree(field);
2259			RETURN_TRUE;
2260		}
2261	}
2262	RETURN_TRUE;
2263}
2264/* }}} */
2265
2266/* {{{ proto int odbc_result_all(resource result_id [, string format])
2267   Print result as HTML table */
2268PHP_FUNCTION(odbc_result_all)
2269{
2270	char *buf = NULL;
2271	odbc_result *result;
2272	RETCODE rc;
2273	zval *pv_res;
2274	char *pv_format = NULL;
2275	size_t i, pv_format_len = 0;
2276	SQLSMALLINT sql_c_type;
2277#ifdef HAVE_SQL_EXTENDED_FETCH
2278	SQLULEN crow;
2279	SQLUSMALLINT RowStatus[1];
2280#endif
2281
2282	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|s", &pv_res, &pv_format, &pv_format_len) == FAILURE) {
2283		return;
2284	}
2285
2286	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2287		RETURN_FALSE;
2288	}
2289
2290	if (result->numcols == 0) {
2291		php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
2292		RETURN_FALSE;
2293	}
2294#ifdef HAVE_SQL_EXTENDED_FETCH
2295	if (result->fetch_abs)
2296		rc = SQLExtendedFetch(result->stmt,SQL_FETCH_NEXT,1,&crow,RowStatus);
2297	else
2298#endif
2299		rc = SQLFetch(result->stmt);
2300
2301	if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
2302		php_printf("<h2>No rows found</h2>\n");
2303		RETURN_LONG(0);
2304	}
2305
2306	/* Start table tag */
2307	if (ZEND_NUM_ARGS() == 1) {
2308		php_printf("<table><tr>");
2309	} else {
2310		php_printf("<table %s ><tr>", pv_format);
2311	}
2312
2313	for (i = 0; i < result->numcols; i++) {
2314		php_printf("<th>%s</th>", result->values[i].name);
2315	}
2316
2317	php_printf("</tr>\n");
2318
2319	while(rc == SQL_SUCCESS || rc == SQL_SUCCESS_WITH_INFO) {
2320		result->fetched++;
2321		php_printf("<tr>");
2322		for(i = 0; i < result->numcols; i++) {
2323			sql_c_type = SQL_C_CHAR;
2324			switch(result->values[i].coltype) {
2325				case SQL_BINARY:
2326				case SQL_VARBINARY:
2327				case SQL_LONGVARBINARY:
2328					if (result->binmode <= 0) {
2329						php_printf("<td>Not printable</td>");
2330						break;
2331					}
2332					if (result->binmode <= 1) sql_c_type = SQL_C_BINARY;
2333				case SQL_LONGVARCHAR:
2334#if defined(ODBCVER) && (ODBCVER >= 0x0300)
2335				case SQL_WLONGVARCHAR:
2336#endif
2337					if (IS_SQL_LONG(result->values[i].coltype) &&
2338						result->longreadlen <= 0) {
2339						php_printf("<td>Not printable</td>");
2340						break;
2341					}
2342
2343					if (buf == NULL) {
2344						buf = emalloc(result->longreadlen);
2345					}
2346
2347					rc = SQLGetData(result->stmt, (SQLUSMALLINT)(i + 1),sql_c_type, buf, result->longreadlen, &result->values[i].vallen);
2348
2349					php_printf("<td>");
2350
2351					if (rc == SQL_ERROR) {
2352						odbc_sql_error(result->conn_ptr, result->stmt, "SQLGetData");
2353						php_printf("</td></tr></table>");
2354						efree(buf);
2355						RETURN_FALSE;
2356					}
2357					if (rc == SQL_SUCCESS_WITH_INFO) {
2358						PHPWRITE(buf, result->longreadlen);
2359					} else if (result->values[i].vallen == SQL_NULL_DATA) {
2360						php_printf("<td>NULL</td>");
2361						break;
2362					} else {
2363						PHPWRITE(buf, result->values[i].vallen);
2364					}
2365					php_printf("</td>");
2366					break;
2367				default:
2368					if (result->values[i].vallen == SQL_NULL_DATA) {
2369						php_printf("<td>NULL</td>");
2370					} else {
2371						php_printf("<td>%s</td>", result->values[i].value);
2372					}
2373					break;
2374			}
2375		}
2376   		php_printf("</tr>\n");
2377
2378#ifdef HAVE_SQL_EXTENDED_FETCH
2379		if (result->fetch_abs)
2380			rc = SQLExtendedFetch(result->stmt,SQL_FETCH_NEXT,1,&crow,RowStatus);
2381		else
2382#endif
2383			rc = SQLFetch(result->stmt);
2384	}
2385	php_printf("</table>\n");
2386	if (buf) efree(buf);
2387	RETURN_LONG(result->fetched);
2388}
2389/* }}} */
2390
2391/* {{{ proto bool odbc_free_result(resource result_id)
2392   Free resources associated with a result */
2393PHP_FUNCTION(odbc_free_result)
2394{
2395	zval *pv_res;
2396	odbc_result *result;
2397	int i;
2398
2399	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_res) == FAILURE) {
2400		return;
2401	}
2402
2403	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2404		RETURN_FALSE;
2405	}
2406
2407	if (result->values) {
2408		for (i = 0; i < result->numcols; i++) {
2409			if (result->values[i].value) {
2410				efree(result->values[i].value);
2411			}
2412		}
2413		efree(result->values);
2414		result->values = NULL;
2415	}
2416
2417	zend_list_close(Z_RES_P(pv_res));
2418
2419	RETURN_TRUE;
2420}
2421/* }}} */
2422
2423/* {{{ proto resource odbc_connect(string DSN, string user, string password [, int cursor_option])
2424   Connect to a datasource */
2425PHP_FUNCTION(odbc_connect)
2426{
2427	odbc_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
2428}
2429/* }}} */
2430
2431/* {{{ proto resource odbc_pconnect(string DSN, string user, string password [, int cursor_option])
2432   Establish a persistent connection to a datasource */
2433PHP_FUNCTION(odbc_pconnect)
2434{
2435	odbc_do_connect(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
2436}
2437/* }}} */
2438
2439/* {{{ odbc_sqlconnect */
2440int odbc_sqlconnect(odbc_connection **conn, char *db, char *uid, char *pwd, int cur_opt, int persistent)
2441{
2442	RETCODE rc;
2443
2444	*conn = (odbc_connection *)pemalloc(sizeof(odbc_connection), persistent);
2445	(*conn)->persistent = persistent;
2446	SQLAllocEnv(&((*conn)->henv));
2447	SQLAllocConnect((*conn)->henv, &((*conn)->hdbc));
2448
2449#if defined(HAVE_SOLID) || defined(HAVE_SOLID_30)
2450	SQLSetConnectOption((*conn)->hdbc, SQL_TRANSLATE_OPTION,
2451			SQL_SOLID_XLATOPT_NOCNV);
2452#endif
2453#ifdef HAVE_ODBC_ROUTER
2454	{
2455#define CONNSTRSIZE 2048
2456	 char *lpszConnStr = emalloc(CONNSTRSIZE);
2457	 if (lpszConnStr && db) {
2458		 short cbszConnStr;
2459		 if (strstr(db, ";")) {
2460			 /* the caller has apparently passed a connection-string */
2461			 if (strstr(db, "uid") || strstr(db, "UID")) {
2462				 uid = NULL;
2463			 }
2464			 if (strstr(db, "pwd") || strstr(db, "PWD")) {
2465				 pwd = NULL;
2466			 }
2467			 strlcpy( lpszConnStr, db, CONNSTRSIZE);
2468		 }
2469		 else {
2470			 strcpy(lpszConnStr, "DSN=");
2471			 strlcat(lpszConnStr, db, CONNSTRSIZE);
2472		 }
2473		 if (uid) {
2474			 if (uid[0]) {
2475				 strlcat(lpszConnStr, ";UID=", CONNSTRSIZE);
2476				 strlcat(lpszConnStr, uid, CONNSTRSIZE);
2477				 strlcat(lpszConnStr, ";", CONNSTRSIZE);
2478			 }
2479			 if (pwd) {
2480				 if (pwd[0]) {
2481					 strlcat(lpszConnStr, "PWD=", CONNSTRSIZE);
2482					 strlcat(lpszConnStr, pwd, CONNSTRSIZE);
2483					 strlcat(lpszConnStr, ";", CONNSTRSIZE);
2484				 }
2485			 }
2486		 }
2487		 rc = SQLDriverConnect((*conn)->hdbc, NULL, lpszConnStr, SQL_NTS, lpszConnStr, CONNSTRSIZE, &cbszConnStr, SQL_DRIVER_NOPROMPT);
2488		 efree(lpszConnStr);
2489	 }
2490	}
2491#else
2492#ifdef HAVE_OPENLINK
2493	{
2494		char dsnbuf[1024];
2495		short dsnbuflen;
2496
2497		rc = SQLDriverConnect((*conn)->hdbc, NULL, db, SQL_NTS,	dsnbuf, sizeof(dsnbuf) - 1, &dsnbuflen, SQL_DRIVER_NOPROMPT);
2498	}
2499#else
2500	if (cur_opt != SQL_CUR_DEFAULT) {
2501		rc = SQLSetConnectOption((*conn)->hdbc, SQL_ODBC_CURSORS, cur_opt);
2502		if (rc != SQL_SUCCESS) {  /* && rc != SQL_SUCCESS_WITH_INFO ? */
2503			odbc_sql_error(*conn, SQL_NULL_HSTMT, "SQLSetConnectOption");
2504			SQLFreeConnect((*conn)->hdbc);
2505			pefree(*conn, persistent);
2506			return FALSE;
2507		}
2508	}
2509/*  Possible fix for bug #10250
2510 *  Needs testing on UnixODBC < 2.0.5 though. */
2511#if defined(HAVE_EMPRESS) || defined(HAVE_UNIXODBC) || defined(PHP_WIN32) || defined (HAVE_IODBC)
2512/* *  Uncomment the line above, and comment line below to fully test
2513 * #ifdef HAVE_EMPRESS */
2514	{
2515		int     direct = 0;
2516		char    dsnbuf[1024];
2517		short   dsnbuflen;
2518		char    *ldb = 0;
2519		int		ldb_len = 0;
2520
2521		if (strstr((char*)db, ";")) {
2522			direct = 1;
2523			if (uid && !strstr ((char*)db, "uid") && !strstr((char*)db, "UID")) {
2524				spprintf(&ldb, 0, "%s;UID=%s;PWD=%s", db, uid, pwd);
2525			} else {
2526				ldb_len = strlen(db)+1;
2527				ldb = (char*) emalloc(ldb_len);
2528				memcpy(ldb, db, ldb_len);
2529			}
2530		}
2531
2532		if (direct) {
2533			rc = SQLDriverConnect((*conn)->hdbc, NULL, ldb, strlen(ldb), dsnbuf, sizeof(dsnbuf) - 1, &dsnbuflen, SQL_DRIVER_NOPROMPT);
2534		} else {
2535			rc = SQLConnect((*conn)->hdbc, db, SQL_NTS, uid, SQL_NTS, pwd, SQL_NTS);
2536		}
2537
2538		if (ldb) {
2539			efree(ldb);
2540		}
2541	}
2542#else
2543	rc = SQLConnect((*conn)->hdbc, db, SQL_NTS, uid, SQL_NTS, pwd, SQL_NTS);
2544#endif
2545#endif
2546#endif
2547	if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
2548		odbc_sql_error(*conn, SQL_NULL_HSTMT, "SQLConnect");
2549		SQLFreeConnect((*conn)->hdbc);
2550		pefree((*conn), persistent);
2551		return FALSE;
2552	}
2553/*	(*conn)->open = 1;*/
2554	return TRUE;
2555}
2556/* }}} */
2557
2558/* Persistent connections: two list-types le_pconn, le_conn and a plist
2559 * where hashed connection info is stored together with index pointer to
2560 * the actual link of type le_pconn in the list. Only persistent
2561 * connections get hashed up. Normal connections use existing pconnections.
2562 * Maybe this has to change with regard to transactions on pconnections?
2563 * Possibly set autocommit to on on request shutdown.
2564 *
2565 * We do have to hash non-persistent connections, and reuse connections.
2566 * In the case where two connects were being made, without closing the first
2567 * connect, access violations were occurring.  This is because some of the
2568 * "globals" in this module should actually be per-connection variables.  I
2569 * simply fixed things to get them working for now.  Shane
2570 */
2571/* {{{ odbc_do_connect */
2572void odbc_do_connect(INTERNAL_FUNCTION_PARAMETERS, int persistent)
2573{
2574	char *db, *uid, *pwd;
2575	size_t db_len, uid_len, pwd_len;
2576	zend_long pv_opt = SQL_CUR_DEFAULT;
2577	odbc_connection *db_conn;
2578	char *hashed_details;
2579	int hashed_len, cur_opt;
2580
2581	/*  Now an optional 4th parameter specifying the cursor type
2582	 *  defaulting to the cursors default
2583	 */
2584	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sss|l", &db, &db_len, &uid, &uid_len, &pwd, &pwd_len, &pv_opt) == FAILURE) {
2585		return;
2586	}
2587
2588	cur_opt = pv_opt;
2589
2590	if (ZEND_NUM_ARGS() > 3) {
2591		/* Confirm the cur_opt range */
2592		if (! (cur_opt == SQL_CUR_USE_IF_NEEDED ||
2593			cur_opt == SQL_CUR_USE_ODBC ||
2594			cur_opt == SQL_CUR_USE_DRIVER ||
2595			cur_opt == SQL_CUR_DEFAULT) ) {
2596			php_error_docref(NULL, E_WARNING, "Invalid Cursor type (%d)", cur_opt);
2597			RETURN_FALSE;
2598		}
2599	}
2600
2601	if (ODBCG(allow_persistent) <= 0) {
2602		persistent = 0;
2603	}
2604
2605	hashed_len = spprintf(&hashed_details, 0, "%s_%s_%s_%s_%d", ODBC_TYPE, db, uid, pwd, cur_opt);
2606
2607	/* FIXME the idea of checking to see if our connection is already persistent
2608		is good, but it adds a lot of overhead to non-persistent connections.  We
2609		should look and see if we can fix that somehow */
2610	/* try to find if we already have this link in our persistent list,
2611	 * no matter if it is to be persistent or not
2612	 */
2613
2614try_and_get_another_connection:
2615
2616	if (persistent) {
2617		zend_resource *le;
2618
2619		/* the link is not in the persistent list */
2620		if ((le = zend_hash_str_find_ptr(&EG(persistent_list), hashed_details, hashed_len)) == NULL) {
2621			zend_resource new_le;
2622
2623			if (ODBCG(max_links) != -1 && ODBCG(num_links) >= ODBCG(max_links)) {
2624				php_error_docref(NULL, E_WARNING, "Too many open links (%ld)", ODBCG(num_links));
2625				efree(hashed_details);
2626				RETURN_FALSE;
2627			}
2628			if (ODBCG(max_persistent) != -1 && ODBCG(num_persistent) >= ODBCG(max_persistent)) {
2629				php_error_docref(NULL, E_WARNING,"Too many open persistent links (%ld)", ODBCG(num_persistent));
2630				efree(hashed_details);
2631				RETURN_FALSE;
2632			}
2633
2634			if (!odbc_sqlconnect(&db_conn, db, uid, pwd, cur_opt, 1)) {
2635				efree(hashed_details);
2636				RETURN_FALSE;
2637			}
2638
2639			new_le.type = le_pconn;
2640			new_le.ptr = db_conn;
2641			new_le.handle = -1;
2642			if (zend_hash_str_update_mem(&EG(persistent_list), hashed_details, hashed_len, &new_le,
2643						sizeof(zend_resource)) == NULL) {
2644				free(db_conn);
2645				efree(hashed_details);
2646				RETURN_FALSE;
2647			}
2648			ODBCG(num_persistent)++;
2649			ODBCG(num_links)++;
2650			db_conn->res = zend_register_resource(db_conn, le_pconn);
2651			RETVAL_RES(db_conn->res);
2652		} else { /* found connection */
2653			if (le->type != le_pconn) {
2654				RETURN_FALSE;
2655			}
2656			/*
2657			 * check to see if the connection is still valid
2658			 */
2659			db_conn = (odbc_connection *)le->ptr;
2660
2661			/*
2662			 * check to see if the connection is still in place (lurcher)
2663			 */
2664			if(ODBCG(check_persistent)){
2665				RETCODE ret;
2666				UCHAR d_name[32];
2667				SQLSMALLINT len;
2668
2669				ret = SQLGetInfo(db_conn->hdbc,
2670					SQL_DATA_SOURCE_READ_ONLY,
2671					d_name, sizeof(d_name), &len);
2672
2673				if(ret != SQL_SUCCESS || len == 0) {
2674					zend_hash_str_del(&EG(persistent_list), hashed_details, hashed_len);
2675					/* Commented out to fix a possible double closure error
2676					 * when working with persistent connections as submitted by
2677					 * bug #15758
2678					 *
2679					 * safe_odbc_disconnect(db_conn->hdbc);
2680					 * SQLFreeConnect(db_conn->hdbc);
2681					 */
2682					goto try_and_get_another_connection;
2683				}
2684			}
2685		}
2686		db_conn->res = zend_register_resource(db_conn, le_pconn);
2687		RETVAL_RES(db_conn->res);
2688	} else { /* non persistent */
2689		zend_resource *index_ptr, new_index_ptr;
2690
2691		if ((index_ptr = zend_hash_str_find_ptr(&EG(regular_list), hashed_details, hashed_len)) != NULL) {
2692			zend_ulong conn_id;
2693			zend_resource *p;
2694
2695			if (index_ptr->type != le_index_ptr) {
2696				RETURN_FALSE;
2697			}
2698			conn_id = (zend_ulong)index_ptr->ptr;
2699			p = zend_hash_index_find_ptr(&EG(regular_list), conn_id);   /* check if the connection is still there */
2700
2701			if (p && p->ptr && (p->type == le_conn || p->type == le_pconn)) {
2702				GC_REFCOUNT(p)++;
2703				RETVAL_RES(p);
2704				efree(hashed_details);
2705				return;
2706			} else {
2707				zend_hash_str_del(&EG(regular_list), hashed_details, hashed_len);
2708			}
2709		}
2710		if (ODBCG(max_links) != -1 && ODBCG(num_links) >= ODBCG(max_links)) {
2711			php_error_docref(NULL, E_WARNING,"Too many open connections (%ld)",ODBCG(num_links));
2712			efree(hashed_details);
2713			RETURN_FALSE;
2714		}
2715
2716		if (!odbc_sqlconnect(&db_conn, db, uid, pwd, cur_opt, 0)) {
2717			efree(hashed_details);
2718			RETURN_FALSE;
2719		}
2720		db_conn->res = zend_register_resource(db_conn, le_conn);
2721		RETVAL_RES(db_conn->res);
2722		new_index_ptr.ptr = (void *)(zend_uintptr_t)Z_RES_HANDLE_P(return_value);
2723		new_index_ptr.type = le_index_ptr;
2724
2725		if (zend_hash_str_update_mem(&EG(regular_list), hashed_details, hashed_len, (void *) &new_index_ptr,
2726				   sizeof(zend_resource)) == NULL) {
2727			efree(hashed_details);
2728			RETURN_FALSE;
2729			/* XXX Free Connection */
2730		}
2731		ODBCG(num_links)++;
2732	}
2733	efree(hashed_details);
2734}
2735/* }}} */
2736
2737/* {{{ proto void odbc_close(resource connection_id)
2738   Close an ODBC connection */
2739PHP_FUNCTION(odbc_close)
2740{
2741	zval *pv_conn;
2742	zend_resource *p;
2743	odbc_connection *conn;
2744	odbc_result *res;
2745	int is_pconn = 0;
2746
2747	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_conn) == FAILURE) {
2748		return;
2749	}
2750
2751	conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn);
2752	if (Z_RES_P(pv_conn)->type == le_pconn) {
2753		is_pconn = 1;
2754	}
2755
2756	ZEND_HASH_FOREACH_PTR(&EG(regular_list), p) {
2757		if (p->ptr && (p->type == le_result)) {
2758			res = (odbc_result *)p->ptr;
2759			if (res->conn_ptr == conn) {
2760				zend_list_close(p);
2761			}
2762		}
2763	} ZEND_HASH_FOREACH_END();
2764
2765	zend_list_close(Z_RES_P(pv_conn));
2766
2767	if(is_pconn){
2768		zend_hash_apply_with_argument(&EG(persistent_list),	(apply_func_arg_t) _close_pconn_with_res, (void *) Z_RES_P(pv_conn));
2769	}
2770}
2771/* }}} */
2772
2773/* {{{ proto int odbc_num_rows(resource result_id)
2774   Get number of rows in a result */
2775PHP_FUNCTION(odbc_num_rows)
2776{
2777	odbc_result *result;
2778	SQLLEN rows;
2779	zval *pv_res;
2780
2781	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_res) == FAILURE) {
2782		return;
2783	}
2784
2785	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2786		RETURN_FALSE;
2787	}
2788
2789	SQLRowCount(result->stmt, &rows);
2790	RETURN_LONG(rows);
2791}
2792/* }}} */
2793
2794#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30)
2795/* {{{ proto bool odbc_next_result(resource result_id)
2796   Checks if multiple results are available */
2797PHP_FUNCTION(odbc_next_result)
2798{
2799	odbc_result *result;
2800	zval *pv_res;
2801	int rc, i;
2802
2803	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_res) == FAILURE) {
2804		return;
2805	}
2806
2807	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2808		RETURN_FALSE;
2809	}
2810
2811	if (result->values) {
2812		for(i = 0; i < result->numcols; i++) {
2813			if (result->values[i].value) {
2814				efree(result->values[i].value);
2815			}
2816		}
2817		efree(result->values);
2818		result->values = NULL;
2819	}
2820
2821	result->fetched = 0;
2822	rc = SQLMoreResults(result->stmt);
2823	if (rc == SQL_SUCCESS_WITH_INFO || rc == SQL_SUCCESS) {
2824		rc = SQLFreeStmt(result->stmt, SQL_UNBIND);
2825		SQLNumParams(result->stmt, &(result->numparams));
2826		SQLNumResultCols(result->stmt, &(result->numcols));
2827
2828		if (result->numcols > 0) {
2829			if (!odbc_bindcols(result)) {
2830				efree(result);
2831				RETVAL_FALSE;
2832			}
2833		} else {
2834			result->values = NULL;
2835		}
2836		RETURN_TRUE;
2837	} else if (rc == SQL_NO_DATA_FOUND) {
2838		RETURN_FALSE;
2839	} else {
2840		odbc_sql_error(result->conn_ptr, result->stmt, "SQLMoreResults");
2841		RETURN_FALSE;
2842	}
2843}
2844/* }}} */
2845#endif
2846
2847/* {{{ proto int odbc_num_fields(resource result_id)
2848   Get number of columns in a result */
2849PHP_FUNCTION(odbc_num_fields)
2850{
2851	odbc_result *result;
2852	zval *pv_res;
2853
2854	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &pv_res) == FAILURE) {
2855		return;
2856	}
2857
2858	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2859		RETURN_FALSE;
2860	}
2861
2862	RETURN_LONG(result->numcols);
2863}
2864/* }}} */
2865
2866/* {{{ proto string odbc_field_name(resource result_id, int field_number)
2867   Get a column name */
2868PHP_FUNCTION(odbc_field_name)
2869{
2870	odbc_result *result;
2871	zval *pv_res;
2872	zend_long pv_num;
2873
2874	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &pv_res, &pv_num) == FAILURE) {
2875		return;
2876	}
2877
2878	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2879		RETURN_FALSE;
2880	}
2881
2882	if (result->numcols == 0) {
2883		php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
2884		RETURN_FALSE;
2885	}
2886
2887	if (pv_num > result->numcols) {
2888		php_error_docref(NULL, E_WARNING, "Field index larger than number of fields");
2889		RETURN_FALSE;
2890	}
2891
2892	if (pv_num < 1) {
2893		php_error_docref(NULL, E_WARNING, "Field numbering starts at 1");
2894		RETURN_FALSE;
2895	}
2896
2897	RETURN_STRING(result->values[pv_num - 1].name);
2898}
2899/* }}} */
2900
2901/* {{{ proto string odbc_field_type(resource result_id, int field_number)
2902   Get the datatype of a column */
2903PHP_FUNCTION(odbc_field_type)
2904{
2905	odbc_result	*result;
2906	char    	tmp[32];
2907	SQLSMALLINT	tmplen;
2908	zval		*pv_res;
2909	zend_long		pv_num;
2910
2911	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl", &pv_res, &pv_num) == FAILURE) {
2912		return;
2913	}
2914
2915	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2916		RETURN_FALSE;
2917	}
2918
2919	if (result->numcols == 0) {
2920		php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
2921		RETURN_FALSE;
2922	}
2923
2924	if (pv_num > result->numcols) {
2925		php_error_docref(NULL, E_WARNING, "Field index larger than number of fields");
2926		RETURN_FALSE;
2927	}
2928
2929	if (pv_num < 1) {
2930		php_error_docref(NULL, E_WARNING, "Field numbering starts at 1");
2931		RETURN_FALSE;
2932	}
2933
2934	PHP_ODBC_SQLCOLATTRIBUTE(result->stmt, (SQLUSMALLINT)pv_num, SQL_COLUMN_TYPE_NAME, tmp, 31, &tmplen, NULL);
2935	RETURN_STRING(tmp)
2936}
2937/* }}} */
2938
2939/* {{{ proto int odbc_field_len(resource result_id, int field_number)
2940   Get the length (precision) of a column */
2941PHP_FUNCTION(odbc_field_len)
2942{
2943	odbc_column_lengths(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
2944}
2945/* }}} */
2946
2947/* {{{ proto int odbc_field_scale(resource result_id, int field_number)
2948   Get the scale of a column */
2949PHP_FUNCTION(odbc_field_scale)
2950{
2951	odbc_column_lengths(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
2952}
2953/* }}} */
2954
2955/* {{{ proto int odbc_field_num(resource result_id, string field_name)
2956   Return column number */
2957PHP_FUNCTION(odbc_field_num)
2958{
2959	char *fname;
2960	size_t i, field_ind, fname_len;
2961	odbc_result *result;
2962	zval *pv_res;
2963
2964	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &pv_res, &fname, &fname_len) == FAILURE) {
2965		return;
2966	}
2967
2968	if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_res), "ODBC result", le_result)) == NULL) {
2969		RETURN_FALSE;
2970	}
2971
2972	if (result->numcols == 0) {
2973		php_error_docref(NULL, E_WARNING, "No tuples available at this result index");
2974		RETURN_FALSE;
2975	}
2976
2977	field_ind = -1;
2978	for(i = 0; i < result->numcols; i++) {
2979		if (strcasecmp(result->values[i].name, fname) == 0) {
2980			field_ind = i + 1;
2981		}
2982	}
2983
2984	if (field_ind == -1) {
2985		RETURN_FALSE;
2986	}
2987	RETURN_LONG(field_ind);
2988}
2989/* }}} */
2990
2991/* {{{ proto mixed odbc_autocommit(resource connection_id [, int OnOff])
2992   Toggle autocommit mode or get status */
2993/* There can be problems with pconnections!*/
2994PHP_FUNCTION(odbc_autocommit)
2995{
2996	odbc_connection *conn;
2997	RETCODE rc;
2998	zval *pv_conn;
2999	zend_long pv_onoff = 0;
3000
3001	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &pv_conn, &pv_onoff) == FAILURE) {
3002		return;
3003	}
3004
3005	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3006		RETURN_FALSE;
3007	}
3008
3009	if (ZEND_NUM_ARGS() > 1) {
3010		rc = SQLSetConnectOption(conn->hdbc, SQL_AUTOCOMMIT, (pv_onoff) ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF);
3011		if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
3012			odbc_sql_error(conn, SQL_NULL_HSTMT, "Set autocommit");
3013			RETURN_FALSE;
3014		}
3015		RETVAL_TRUE;
3016	} else {
3017		SQLINTEGER status;
3018
3019		rc = SQLGetConnectOption(conn->hdbc, SQL_AUTOCOMMIT, (PTR)&status);
3020		if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
3021			odbc_sql_error(conn, SQL_NULL_HSTMT, "Get commit status");
3022			RETURN_FALSE;
3023		}
3024		RETVAL_LONG((zend_long)status);
3025	}
3026}
3027/* }}} */
3028
3029/* {{{ proto bool odbc_commit(resource connection_id)
3030   Commit an ODBC transaction */
3031PHP_FUNCTION(odbc_commit)
3032{
3033	odbc_transact(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
3034}
3035/* }}} */
3036
3037/* {{{ proto bool odbc_rollback(resource connection_id)
3038   Rollback a transaction */
3039PHP_FUNCTION(odbc_rollback)
3040{
3041	odbc_transact(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
3042}
3043/* }}} */
3044
3045/* {{{ php_odbc_lasterror */
3046static void php_odbc_lasterror(INTERNAL_FUNCTION_PARAMETERS, int mode)
3047{
3048	odbc_connection *conn;
3049	zval *pv_handle;
3050	zend_string *ptr;
3051	int len;
3052
3053	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|r", &pv_handle) == FAILURE) {
3054		return;
3055	}
3056
3057	if (mode == 0) {  /* last state */
3058		len = 6;
3059	} else { /* last error message */
3060		len = SQL_MAX_MESSAGE_LENGTH;
3061	}
3062
3063	if (ZEND_NUM_ARGS() == 1) {
3064		if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_handle), "ODBC-Link", le_conn, le_pconn))) {
3065			RETURN_FALSE;
3066		}
3067		ptr = zend_string_alloc(len + 1, 0);
3068		if (mode == 0) {
3069			strlcpy(ZSTR_VAL(ptr), conn->laststate, len+1);
3070		} else {
3071			strlcpy(ZSTR_VAL(ptr), conn->lasterrormsg, len+1);
3072		}
3073	} else {
3074		ptr = zend_string_alloc(len, 0);
3075		if (mode == 0) {
3076			strlcpy(ZSTR_VAL(ptr), ODBCG(laststate), len+1);
3077		} else {
3078			strlcpy(ZSTR_VAL(ptr), ODBCG(lasterrormsg), len+1);
3079		}
3080	}
3081	RETVAL_STR(ptr);
3082}
3083/* }}} */
3084
3085/* {{{ proto string odbc_error([resource connection_id])
3086   Get the last error code */
3087PHP_FUNCTION(odbc_error)
3088{
3089	php_odbc_lasterror(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
3090}
3091/* }}} */
3092
3093/* {{{ proto string odbc_errormsg([resource connection_id])
3094   Get the last error message */
3095PHP_FUNCTION(odbc_errormsg)
3096{
3097	php_odbc_lasterror(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
3098}
3099/* }}} */
3100
3101/* {{{ proto bool odbc_setoption(resource conn_id|result_id, int which, int option, int value)
3102   Sets connection or statement options */
3103/* This one has to be used carefully. We can't allow to set connection options for
3104   persistent connections. I think that SetStmtOption is of little use, since most
3105   of those can only be specified before preparing/executing statements.
3106   On the other hand, they can be made connection wide default through SetConnectOption
3107   - but will be overidden by calls to SetStmtOption() in odbc_prepare/odbc_do
3108*/
3109PHP_FUNCTION(odbc_setoption)
3110{
3111	odbc_connection *conn;
3112	odbc_result	*result;
3113	RETCODE rc;
3114	zval *pv_handle;
3115	zend_long pv_which, pv_opt, pv_val;
3116
3117	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rlll", &pv_handle, &pv_which, &pv_opt, &pv_val) == FAILURE) {
3118		return;
3119	}
3120
3121	switch (pv_which) {
3122		case 1:		/* SQLSetConnectOption */
3123			if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_handle), "ODBC-Link", le_conn, le_pconn))) {
3124				RETURN_FALSE;
3125			}
3126
3127			if (conn->persistent) {
3128				php_error_docref(NULL, E_WARNING, "Unable to set option for persistent connection");
3129				RETURN_FALSE;
3130			}
3131			rc = SQLSetConnectOption(conn->hdbc, (unsigned short) pv_opt, pv_val);
3132			if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
3133				odbc_sql_error(conn, SQL_NULL_HSTMT, "SetConnectOption");
3134				RETURN_FALSE;
3135			}
3136			break;
3137		case 2:		/* SQLSetStmtOption */
3138			if ((result = (odbc_result *)zend_fetch_resource(Z_RES_P(pv_handle), "ODBC result", le_result)) == NULL) {
3139				RETURN_FALSE;
3140			}
3141
3142			rc = SQLSetStmtOption(result->stmt, (unsigned short) pv_opt, pv_val);
3143
3144			if (rc != SQL_SUCCESS && rc != SQL_SUCCESS_WITH_INFO) {
3145				odbc_sql_error(result->conn_ptr, result->stmt, "SetStmtOption");
3146				RETURN_FALSE;
3147			}
3148			break;
3149		default:
3150			php_error_docref(NULL, E_WARNING, "Unknown option type");
3151			RETURN_FALSE;
3152			break;
3153	}
3154
3155	RETURN_TRUE;
3156}
3157/* }}} */
3158
3159/*
3160 * metadata functions
3161 */
3162
3163/* {{{ proto resource odbc_tables(resource connection_id [, string qualifier [, string owner [, string name [, string table_types]]]])
3164   Call the SQLTables function */
3165PHP_FUNCTION(odbc_tables)
3166{
3167	zval *pv_conn;
3168	odbc_result   *result = NULL;
3169	odbc_connection *conn;
3170	char *cat = NULL, *schema = NULL, *table = NULL, *type = NULL;
3171	size_t cat_len = 0, schema_len = 0, table_len = 0, type_len = 0;
3172	RETCODE rc;
3173
3174	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|s!sss", &pv_conn, &cat, &cat_len, &schema, &schema_len,
3175		&table, &table_len, &type, &type_len) == FAILURE) {
3176		return;
3177	}
3178
3179	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3180		RETURN_FALSE;
3181	}
3182
3183	result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3184
3185	rc = PHP_ODBC_SQLALLOCSTMT(conn->hdbc, &(result->stmt));
3186	if (rc == SQL_INVALID_HANDLE) {
3187		efree(result);
3188		php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3189		RETURN_FALSE;
3190	}
3191
3192	if (rc == SQL_ERROR) {
3193		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3194		efree(result);
3195		RETURN_FALSE;
3196	}
3197
3198	/* This hack is needed to access table information in Access databases (fmk) */
3199	if (table && table_len && schema && schema_len == 0) {
3200		schema = NULL;
3201	}
3202
3203	rc = SQLTables(result->stmt,
3204			cat, SAFE_SQL_NTS(cat),
3205			schema,	SAFE_SQL_NTS(schema),
3206			table, SAFE_SQL_NTS(table),
3207			type, SAFE_SQL_NTS(type));
3208
3209	if (rc == SQL_ERROR) {
3210		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLTables");
3211		efree(result);
3212		RETURN_FALSE;
3213	}
3214
3215	result->numparams = 0;
3216	SQLNumResultCols(result->stmt, &(result->numcols));
3217
3218	if (result->numcols > 0) {
3219		if (!odbc_bindcols(result)) {
3220			efree(result);
3221			RETURN_FALSE;
3222		}
3223	} else {
3224		result->values = NULL;
3225	}
3226	result->conn_ptr = conn;
3227	result->fetched = 0;
3228	RETURN_RES(zend_register_resource(result, le_result));
3229}
3230/* }}} */
3231
3232/* {{{ proto resource odbc_columns(resource connection_id [, string qualifier [, string owner [, string table_name [, string column_name]]]])
3233   Returns a result identifier that can be used to fetch a list of column names in specified tables */
3234PHP_FUNCTION(odbc_columns)
3235{
3236	zval *pv_conn;
3237	odbc_result *result = NULL;
3238	odbc_connection *conn;
3239	char *cat = NULL, *schema = NULL, *table = NULL, *column = NULL;
3240	size_t cat_len = 0, schema_len = 0, table_len = 0, column_len = 0;
3241	RETCODE rc;
3242
3243	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|s!sss", &pv_conn, &cat, &cat_len, &schema, &schema_len,
3244		&table, &table_len, &column, &column_len) == FAILURE) {
3245		return;
3246	}
3247
3248	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3249		RETURN_FALSE;
3250	}
3251
3252	result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3253
3254	rc = PHP_ODBC_SQLALLOCSTMT(conn->hdbc, &(result->stmt));
3255	if (rc == SQL_INVALID_HANDLE) {
3256		efree(result);
3257		php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3258		RETURN_FALSE;
3259	}
3260
3261	if (rc == SQL_ERROR) {
3262		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3263		efree(result);
3264		RETURN_FALSE;
3265	}
3266
3267	/*
3268	 * Needed to make MS Access happy
3269	 */
3270	if (table && table_len && schema && schema_len == 0) {
3271		schema = NULL;
3272	}
3273
3274	rc = SQLColumns(result->stmt,
3275			cat, (SQLSMALLINT) cat_len,
3276			schema, (SQLSMALLINT) schema_len,
3277			table, (SQLSMALLINT) table_len,
3278			column, (SQLSMALLINT) column_len);
3279
3280	if (rc == SQL_ERROR) {
3281		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLColumns");
3282		efree(result);
3283		RETURN_FALSE;
3284	}
3285
3286	result->numparams = 0;
3287	SQLNumResultCols(result->stmt, &(result->numcols));
3288
3289	if (result->numcols > 0) {
3290		if (!odbc_bindcols(result)) {
3291			efree(result);
3292			RETURN_FALSE;
3293		}
3294	} else {
3295		result->values = NULL;
3296	}
3297	result->conn_ptr = conn;
3298	result->fetched = 0;
3299	RETURN_RES(zend_register_resource(result, le_result));
3300}
3301/* }}} */
3302
3303#if !defined(HAVE_DBMAKER) && !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) && !defined(HAVE_SOLID_35) && !defined(HAVE_BIRDSTEP)
3304/* {{{ proto resource odbc_columnprivileges(resource connection_id, string catalog, string schema, string table, string column)
3305   Returns a result identifier that can be used to fetch a list of columns and associated privileges for the specified table */
3306PHP_FUNCTION(odbc_columnprivileges)
3307{
3308	zval *pv_conn;
3309	odbc_result *result = NULL;
3310	odbc_connection *conn;
3311	char *cat = NULL, *schema, *table, *column;
3312	size_t cat_len = 0, schema_len, table_len, column_len;
3313	RETCODE rc;
3314
3315	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs!sss", &pv_conn, &cat, &cat_len, &schema, &schema_len,
3316		&table, &table_len, &column, &column_len) == FAILURE) {
3317		return;
3318	}
3319
3320	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3321		RETURN_FALSE;
3322	}
3323
3324	result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3325
3326	rc = PHP_ODBC_SQLALLOCSTMT(conn->hdbc, &(result->stmt));
3327	if (rc == SQL_INVALID_HANDLE) {
3328		efree(result);
3329		php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3330		RETURN_FALSE;
3331	}
3332
3333	if (rc == SQL_ERROR) {
3334		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3335		efree(result);
3336		RETURN_FALSE;
3337	}
3338
3339	rc = SQLColumnPrivileges(result->stmt,
3340			cat, SAFE_SQL_NTS(cat),
3341			schema, SAFE_SQL_NTS(schema),
3342			table, SAFE_SQL_NTS(table),
3343			column, SAFE_SQL_NTS(column));
3344
3345	if (rc == SQL_ERROR) {
3346		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLColumnPrivileges");
3347		efree(result);
3348		RETURN_FALSE;
3349	}
3350
3351	result->numparams = 0;
3352	SQLNumResultCols(result->stmt, &(result->numcols));
3353
3354	if (result->numcols > 0) {
3355		if (!odbc_bindcols(result)) {
3356			efree(result);
3357			RETURN_FALSE;
3358		}
3359	} else {
3360		result->values = NULL;
3361	}
3362	result->conn_ptr = conn;
3363	result->fetched = 0;
3364	RETURN_RES(zend_register_resource(result, le_result));
3365}
3366/* }}} */
3367#endif /* HAVE_DBMAKER || HAVE_SOLID*/
3368
3369#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) && !defined(HAVE_SOLID_35)
3370/* {{{ proto resource odbc_foreignkeys(resource connection_id, string pk_qualifier, string pk_owner, string pk_table, string fk_qualifier, string fk_owner, string fk_table)
3371   Returns a result identifier to either a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table */
3372PHP_FUNCTION(odbc_foreignkeys)
3373{
3374	zval *pv_conn;
3375	odbc_result *result = NULL;
3376	odbc_connection *conn;
3377	char *pcat = NULL, *pschema, *ptable, *fcat, *fschema, *ftable;
3378	size_t pcat_len = 0, pschema_len, ptable_len, fcat_len, fschema_len, ftable_len;
3379	RETCODE rc;
3380
3381	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs!sssss", &pv_conn, &pcat, &pcat_len, &pschema, &pschema_len,
3382		&ptable, &ptable_len, &fcat, &fcat_len, &fschema, &fschema_len, &ftable, &ftable_len) == FAILURE) {
3383		return;
3384	}
3385
3386#if defined(HAVE_DBMAKER) || defined(HAVE_IBMDB2)
3387#define EMPTY_TO_NULL(xstr) \
3388	if ((int)strlen((xstr)) == 0) (xstr) = NULL
3389
3390		EMPTY_TO_NULL(pcat);
3391		EMPTY_TO_NULL(pschema);
3392		EMPTY_TO_NULL(ptable);
3393		EMPTY_TO_NULL(fcat);
3394		EMPTY_TO_NULL(fschema);
3395		EMPTY_TO_NULL(ftable);
3396#endif
3397
3398	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3399		RETURN_FALSE;
3400	}
3401
3402	result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3403
3404	rc = PHP_ODBC_SQLALLOCSTMT(conn->hdbc, &(result->stmt));
3405	if (rc == SQL_INVALID_HANDLE) {
3406		efree(result);
3407		php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3408		RETURN_FALSE;
3409	}
3410
3411	if (rc == SQL_ERROR) {
3412		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3413		efree(result);
3414		RETURN_FALSE;
3415	}
3416
3417	rc = SQLForeignKeys(result->stmt,
3418			pcat, SAFE_SQL_NTS(pcat),
3419			pschema, SAFE_SQL_NTS(pschema),
3420			ptable, SAFE_SQL_NTS(ptable),
3421			fcat, SAFE_SQL_NTS(fcat),
3422			fschema, SAFE_SQL_NTS(fschema),
3423			ftable, SAFE_SQL_NTS(ftable) );
3424
3425	if (rc == SQL_ERROR) {
3426		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLForeignKeys");
3427		efree(result);
3428		RETURN_FALSE;
3429	}
3430
3431	result->numparams = 0;
3432	SQLNumResultCols(result->stmt, &(result->numcols));
3433
3434	if (result->numcols > 0) {
3435		if (!odbc_bindcols(result)) {
3436			efree(result);
3437			RETURN_FALSE;
3438		}
3439	} else {
3440		result->values = NULL;
3441	}
3442	result->conn_ptr = conn;
3443	result->fetched = 0;
3444	RETURN_RES(zend_register_resource(result, le_result));
3445}
3446/* }}} */
3447#endif /* HAVE_SOLID */
3448
3449/* {{{ proto resource odbc_gettypeinfo(resource connection_id [, int data_type])
3450   Returns a result identifier containing information about data types supported by the data source */
3451PHP_FUNCTION(odbc_gettypeinfo)
3452{
3453	zval *pv_conn;
3454	zend_long pv_data_type = SQL_ALL_TYPES;
3455	odbc_result *result = NULL;
3456	odbc_connection *conn;
3457	RETCODE rc;
3458	SQLSMALLINT data_type;
3459
3460	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &pv_conn, &pv_data_type) == FAILURE) {
3461		return;
3462	}
3463
3464	data_type = (SQLSMALLINT) pv_data_type;
3465
3466	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3467		RETURN_FALSE;
3468	}
3469
3470	result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3471
3472	rc = PHP_ODBC_SQLALLOCSTMT(conn->hdbc, &(result->stmt));
3473	if (rc == SQL_INVALID_HANDLE) {
3474		efree(result);
3475		php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3476		RETURN_FALSE;
3477	}
3478
3479	if (rc == SQL_ERROR) {
3480		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3481		efree(result);
3482		RETURN_FALSE;
3483	}
3484
3485	rc = SQLGetTypeInfo(result->stmt, data_type );
3486
3487	if (rc == SQL_ERROR) {
3488		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLGetTypeInfo");
3489		efree(result);
3490		RETURN_FALSE;
3491	}
3492
3493	result->numparams = 0;
3494	SQLNumResultCols(result->stmt, &(result->numcols));
3495
3496	if (result->numcols > 0) {
3497		if (!odbc_bindcols(result)) {
3498			efree(result);
3499			RETURN_FALSE;
3500		}
3501	} else {
3502		result->values = NULL;
3503	}
3504	result->conn_ptr = conn;
3505	result->fetched = 0;
3506	RETURN_RES(zend_register_resource(result, le_result));
3507}
3508/* }}} */
3509
3510/* {{{ proto resource odbc_primarykeys(resource connection_id, string qualifier, string owner, string table)
3511   Returns a result identifier listing the column names that comprise the primary key for a table */
3512PHP_FUNCTION(odbc_primarykeys)
3513{
3514	zval *pv_conn;
3515	odbc_result   *result = NULL;
3516	odbc_connection *conn;
3517	char *cat = NULL, *schema = NULL, *table = NULL;
3518	size_t cat_len = 0, schema_len, table_len;
3519	RETCODE rc;
3520
3521	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs!ss", &pv_conn, &cat, &cat_len, &schema, &schema_len, &table, &table_len) == FAILURE) {
3522		return;
3523	}
3524
3525	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3526		RETURN_FALSE;
3527	}
3528
3529	result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3530
3531	rc = PHP_ODBC_SQLALLOCSTMT(conn->hdbc, &(result->stmt));
3532	if (rc == SQL_INVALID_HANDLE) {
3533		efree(result);
3534		php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3535		RETURN_FALSE;
3536	}
3537
3538	if (rc == SQL_ERROR) {
3539		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3540		efree(result);
3541		RETURN_FALSE;
3542	}
3543
3544	rc = SQLPrimaryKeys(result->stmt,
3545			cat, SAFE_SQL_NTS(cat),
3546			schema, SAFE_SQL_NTS(schema),
3547			table, SAFE_SQL_NTS(table) );
3548
3549	if (rc == SQL_ERROR) {
3550		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLPrimaryKeys");
3551		efree(result);
3552		RETURN_FALSE;
3553	}
3554
3555	result->numparams = 0;
3556	SQLNumResultCols(result->stmt, &(result->numcols));
3557
3558	if (result->numcols > 0) {
3559		if (!odbc_bindcols(result)) {
3560			efree(result);
3561			RETURN_FALSE;
3562		}
3563	} else {
3564		result->values = NULL;
3565	}
3566	result->conn_ptr = conn;
3567	result->fetched = 0;
3568	RETURN_RES(zend_register_resource(result, le_result));
3569}
3570/* }}} */
3571
3572#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) && !defined(HAVE_SOLID_35) && !defined(HAVE_BIRDSTEP)
3573/* {{{ proto resource odbc_procedurecolumns(resource connection_id [, string qualifier, string owner, string proc, string column])
3574   Returns a result identifier containing the list of input and output parameters, as well as the columns that make up the result set for the specified procedures */
3575PHP_FUNCTION(odbc_procedurecolumns)
3576{
3577	zval *pv_conn;
3578	odbc_result *result = NULL;
3579	odbc_connection *conn;
3580	char *cat = NULL, *schema = NULL, *proc = NULL, *col = NULL;
3581	size_t cat_len = 0, schema_len = 0, proc_len = 0, col_len = 0;
3582	RETCODE rc;
3583
3584	if (ZEND_NUM_ARGS() != 1 && ZEND_NUM_ARGS() != 5) {
3585		WRONG_PARAM_COUNT;
3586	}
3587
3588	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|s!sss", &pv_conn, &cat, &cat_len, &schema, &schema_len,
3589		&proc, &proc_len, &col, &col_len) == FAILURE) {
3590		return;
3591	}
3592
3593	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3594		RETURN_FALSE;
3595	}
3596
3597	result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3598
3599	rc = PHP_ODBC_SQLALLOCSTMT(conn->hdbc, &(result->stmt));
3600	if (rc == SQL_INVALID_HANDLE) {
3601		efree(result);
3602		php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3603		RETURN_FALSE;
3604	}
3605
3606	if (rc == SQL_ERROR) {
3607		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3608		efree(result);
3609		RETURN_FALSE;
3610	}
3611
3612	rc = SQLProcedureColumns(result->stmt,
3613			cat, SAFE_SQL_NTS(cat),
3614			schema, SAFE_SQL_NTS(schema),
3615			proc, SAFE_SQL_NTS(proc),
3616			col, SAFE_SQL_NTS(col) );
3617
3618	if (rc == SQL_ERROR) {
3619		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLProcedureColumns");
3620		efree(result);
3621		RETURN_FALSE;
3622	}
3623
3624	result->numparams = 0;
3625	SQLNumResultCols(result->stmt, &(result->numcols));
3626
3627	if (result->numcols > 0) {
3628		if (!odbc_bindcols(result)) {
3629			efree(result);
3630			RETURN_FALSE;
3631		}
3632	} else {
3633		result->values = NULL;
3634	}
3635	result->conn_ptr = conn;
3636	result->fetched = 0;
3637	RETURN_RES(zend_register_resource(result, le_result));
3638}
3639/* }}} */
3640#endif /* HAVE_SOLID */
3641
3642#if !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) && !defined(HAVE_SOLID_35)
3643/* {{{ proto resource odbc_procedures(resource connection_id [, string qualifier, string owner, string name])
3644   Returns a result identifier containg the list of procedure names in a datasource */
3645PHP_FUNCTION(odbc_procedures)
3646{
3647	zval *pv_conn;
3648	odbc_result   *result = NULL;
3649	odbc_connection *conn;
3650	char *cat = NULL, *schema = NULL, *proc = NULL;
3651	size_t cat_len = 0, schema_len = 0, proc_len = 0;
3652	RETCODE rc;
3653
3654	if (ZEND_NUM_ARGS() != 1 && ZEND_NUM_ARGS() != 4) {
3655		WRONG_PARAM_COUNT;
3656	}
3657
3658	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|s!ss", &pv_conn, &cat, &cat_len, &schema, &schema_len, &proc, &proc_len) == FAILURE) {
3659		return;
3660	}
3661
3662	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3663		RETURN_FALSE;
3664	}
3665
3666	result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3667
3668	rc = PHP_ODBC_SQLALLOCSTMT(conn->hdbc, &(result->stmt));
3669	if (rc == SQL_INVALID_HANDLE) {
3670		efree(result);
3671		php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3672		RETURN_FALSE;
3673	}
3674
3675	if (rc == SQL_ERROR) {
3676		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3677		efree(result);
3678		RETURN_FALSE;
3679	}
3680
3681	rc = SQLProcedures(result->stmt,
3682			cat, SAFE_SQL_NTS(cat),
3683			schema, SAFE_SQL_NTS(schema),
3684			proc, SAFE_SQL_NTS(proc) );
3685
3686	if (rc == SQL_ERROR) {
3687		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLProcedures");
3688		efree(result);
3689		RETURN_FALSE;
3690	}
3691
3692	result->numparams = 0;
3693	SQLNumResultCols(result->stmt, &(result->numcols));
3694
3695	if (result->numcols > 0) {
3696		if (!odbc_bindcols(result)) {
3697			efree(result);
3698			RETURN_FALSE;
3699		}
3700	} else {
3701		result->values = NULL;
3702	}
3703	result->conn_ptr = conn;
3704	result->fetched = 0;
3705	RETURN_RES(zend_register_resource(result, le_result));
3706}
3707/* }}} */
3708#endif /* HAVE_SOLID */
3709
3710/* {{{ proto resource odbc_specialcolumns(resource connection_id, int type, string qualifier, string owner, string table, int scope, int nullable)
3711   Returns a result identifier containing either the optimal set of columns that uniquely identifies a row in the table or columns that are automatically updated when any value in the row is updated by a transaction */
3712PHP_FUNCTION(odbc_specialcolumns)
3713{
3714	zval *pv_conn;
3715	zend_long vtype, vscope, vnullable;
3716	odbc_result *result = NULL;
3717	odbc_connection *conn;
3718	char *cat = NULL, *schema = NULL, *name = NULL;
3719	size_t cat_len = 0, schema_len, name_len;
3720	SQLUSMALLINT type, scope, nullable;
3721	RETCODE rc;
3722
3723	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rls!ssl", &pv_conn, &vtype, &cat, &cat_len, &schema, &schema_len,
3724		&name, &name_len, &vscope, &vnullable) == FAILURE) {
3725		return;
3726	}
3727
3728	type = (SQLUSMALLINT) vtype;
3729	scope = (SQLUSMALLINT) vscope;
3730	nullable = (SQLUSMALLINT) vnullable;
3731
3732	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3733		RETURN_FALSE;
3734	}
3735
3736	result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3737
3738	rc = PHP_ODBC_SQLALLOCSTMT(conn->hdbc, &(result->stmt));
3739	if (rc == SQL_INVALID_HANDLE) {
3740		efree(result);
3741		php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3742		RETURN_FALSE;
3743	}
3744
3745	if (rc == SQL_ERROR) {
3746		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3747		efree(result);
3748		RETURN_FALSE;
3749	}
3750
3751	rc = SQLSpecialColumns(result->stmt,
3752			type,
3753			cat, SAFE_SQL_NTS(cat),
3754			schema, SAFE_SQL_NTS(schema),
3755			name, SAFE_SQL_NTS(name),
3756			scope,
3757			nullable);
3758
3759	if (rc == SQL_ERROR) {
3760		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLSpecialColumns");
3761		efree(result);
3762		RETURN_FALSE;
3763	}
3764
3765	result->numparams = 0;
3766	SQLNumResultCols(result->stmt, &(result->numcols));
3767
3768	if (result->numcols > 0) {
3769		if (!odbc_bindcols(result)) {
3770			efree(result);
3771			RETURN_FALSE;
3772		}
3773	} else {
3774		result->values = NULL;
3775	}
3776	result->conn_ptr = conn;
3777	result->fetched = 0;
3778	RETURN_RES(zend_register_resource(result, le_result));
3779}
3780/* }}} */
3781
3782/* {{{ proto resource odbc_statistics(resource connection_id, string qualifier, string owner, string name, int unique, int accuracy)
3783   Returns a result identifier that contains statistics about a single table and the indexes associated with the table */
3784PHP_FUNCTION(odbc_statistics)
3785{
3786	zval *pv_conn;
3787	zend_long vunique, vreserved;
3788	odbc_result *result = NULL;
3789	odbc_connection *conn;
3790	char *cat = NULL, *schema, *name;
3791	size_t cat_len = 0, schema_len, name_len;
3792	SQLUSMALLINT unique, reserved;
3793	RETCODE rc;
3794
3795	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs!ssll", &pv_conn, &cat, &cat_len, &schema, &schema_len,
3796		&name, &name_len, &vunique, &vreserved) == FAILURE) {
3797		return;
3798	}
3799
3800	unique = (SQLUSMALLINT) vunique;
3801	reserved = (SQLUSMALLINT) vreserved;
3802
3803	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3804		RETURN_FALSE;
3805	}
3806
3807	result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3808
3809	rc = PHP_ODBC_SQLALLOCSTMT(conn->hdbc, &(result->stmt));
3810	if (rc == SQL_INVALID_HANDLE) {
3811		efree(result);
3812		php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3813		RETURN_FALSE;
3814	}
3815
3816	if (rc == SQL_ERROR) {
3817		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3818		efree(result);
3819		RETURN_FALSE;
3820	}
3821
3822	rc = SQLStatistics(result->stmt,
3823			cat, SAFE_SQL_NTS(cat),
3824			schema, SAFE_SQL_NTS(schema),
3825			name, SAFE_SQL_NTS(name),
3826			unique,
3827			reserved);
3828
3829	if (rc == SQL_ERROR) {
3830		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLStatistics");
3831		efree(result);
3832		RETURN_FALSE;
3833	}
3834
3835	result->numparams = 0;
3836	SQLNumResultCols(result->stmt, &(result->numcols));
3837
3838	if (result->numcols > 0) {
3839		if (!odbc_bindcols(result)) {
3840			efree(result);
3841			RETURN_FALSE;
3842		}
3843	} else {
3844		result->values = NULL;
3845	}
3846	result->conn_ptr = conn;
3847	result->fetched = 0;
3848	RETURN_RES(zend_register_resource(result, le_result));
3849}
3850/* }}} */
3851
3852#if !defined(HAVE_DBMAKER) && !defined(HAVE_SOLID) && !defined(HAVE_SOLID_30) && !defined(HAVE_SOLID_35) && !defined(HAVE_BIRDSTEP)
3853/* {{{ proto resource odbc_tableprivileges(resource connection_id, string qualifier, string owner, string name)
3854   Returns a result identifier containing a list of tables and the privileges associated with each table */
3855PHP_FUNCTION(odbc_tableprivileges)
3856{
3857	zval *pv_conn;
3858	odbc_result   *result = NULL;
3859	odbc_connection *conn;
3860	char *cat = NULL, *schema = NULL, *table = NULL;
3861	size_t cat_len = 0, schema_len, table_len;
3862	RETCODE rc;
3863
3864	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs!ss", &pv_conn, &cat, &cat_len, &schema, &schema_len, &table, &table_len) == FAILURE) {
3865		return;
3866	}
3867
3868	if (!(conn = (odbc_connection *)zend_fetch_resource2(Z_RES_P(pv_conn), "ODBC-Link", le_conn, le_pconn))) {
3869		RETURN_FALSE;
3870	}
3871
3872	result = (odbc_result *)ecalloc(1, sizeof(odbc_result));
3873
3874	rc = PHP_ODBC_SQLALLOCSTMT(conn->hdbc, &(result->stmt));
3875	if (rc == SQL_INVALID_HANDLE) {
3876		efree(result);
3877		php_error_docref(NULL, E_WARNING, "SQLAllocStmt error 'Invalid Handle'");
3878		RETURN_FALSE;
3879	}
3880
3881	if (rc == SQL_ERROR) {
3882		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLAllocStmt");
3883		efree(result);
3884		RETURN_FALSE;
3885	}
3886
3887	rc = SQLTablePrivileges(result->stmt,
3888			cat, SAFE_SQL_NTS(cat),
3889			schema, SAFE_SQL_NTS(schema),
3890			table, SAFE_SQL_NTS(table));
3891
3892	if (rc == SQL_ERROR) {
3893		odbc_sql_error(conn, SQL_NULL_HSTMT, "SQLTablePrivileges");
3894		efree(result);
3895		RETURN_FALSE;
3896	}
3897
3898	result->numparams = 0;
3899	SQLNumResultCols(result->stmt, &(result->numcols));
3900
3901	if (result->numcols > 0) {
3902		if (!odbc_bindcols(result)) {
3903			efree(result);
3904			RETURN_FALSE;
3905		}
3906	} else {
3907		result->values = NULL;
3908	}
3909	result->conn_ptr = conn;
3910	result->fetched = 0;
3911	RETURN_RES(zend_register_resource(result, le_result));
3912}
3913/* }}} */
3914#endif /* HAVE_DBMAKER */
3915
3916#endif /* HAVE_UODBC */
3917
3918/*
3919 * Local variables:
3920 * tab-width: 4
3921 * c-basic-offset: 4
3922 * End:
3923 * vim600: sw=4 ts=4 fdm=marker
3924 * vim<600: sw=4 ts=4
3925 */
3926