<?php

	ini_set('max_execution_time', 0);
	require_once 'auth.php';

	#$rs = $adodb->Execute("SELECT * FROM qb_config ".
	#" WHERE tableid = ? ", array($_POST['tableid']));
	#if ($rs->EOF) {
	#	die('Error: Empty Data (EOF)');
	#}
	#$odbc_dsn = $rs->fields['dsn'];
	#$sql = $rs->fields['sqlimport'];

	$odbc_dsn = $_POST['dsn'];
	$sql = $_POST['sqlimport'];

	if (empty($odbc_dsn)) {
		die("Error: Empty DSN");
	}
	echo "DSN: ".$odbc_dsn."<br>";
	
	$odbc =& ADONewConnection($odbc_dsn);
	if (!$odbc) {
		die($odbc->ErrorMsg());
	}
	$odbc->SetFetchMode(ADODB_FETCH_ASSOC);
	echo "Connect: OK<br/>";
	echo "<hr>";

	$arrTables = $odbc->MetaTables();
	if (!is_array($arrTables) || count($arrTables) == 0) {
		die("Error: Empty MetaTables<br/>".$odbc->ErrorMsg());
	}
	echo "MetaTables: ".count($arrTables)." tables =&gt; ".implode(", ", $arrTables)."<br>";
	echo "<hr>";
 
	if (!$sql) {
		die("Error: Empty SQL Import");
	}
	echo "SQL: ".$sql."<br>";
	echo "<hr>";
	
	$rs = $odbc->Execute($sql);
	if (!is_object($rs)) echo $odbc->ErrorMsg();
	else {
		$arr = array();
		for ($i = 0, $n = $rs->FieldCount(); $i < $n; $i++) {
			$fieldobj = $rs->FetchField($i);
			$arr[] = $fieldobj->name;
		}
		$i = $rs->RecordCount();

		echo "Found ".$n." fields => ".implode(", ", $arr)."<br/>";
		echo "Found ".$i." records.<br>";
		if (!$rs->EOF) echo "First record: '".implode("', '", $rs->fields)."'<br/>";
		echo "<script language=javascript>
		if (opener.document.forms[0].sqlcreate.value == '') {
			opener.document.forms[0].sqlcreate.value = ' ".implode(" varchar(255), \\n  ", $arr).
			" varchar(255)\\n';
		}
		</script>";
	}

?>
