Location: PHPKode > projects > PhpDbEdit > phpDbEdit/phpDbEditSetup.php
<?php

/*
 * phpDbEdit - instant Database table editor and code generator
 *
 * phpDbEditSetup.php - interactive table configuration utility (setup)
 * ____________________________________________________________
 *
 * Database independand version (phpDbEdit)
 * Copyright (c) 2007      Martti Remmelgas <hide@address.com> 
 * 
 * Postgresql version (phpPgEdit)
 * Copyright (c) 2006-2007 Raphael (mc.rraph) Pautasso <hide@address.com>
 * 
 * MySQL version (phpMyEdit)
 * Copyright (c) 1999-2002 John McCreesh <hide@address.com>
 * Copyright (c) 2001-2002 Jim Kraai <hide@address.com>
 * Versions 5.0 and higher developed by Ondrej Jombik <hide@address.com>
 * Copyright (c) 2002-2006 Platon Group, http://platon.sk/
 * All rights reserved.
 *
 * See README file for more information about this software.
 * See COPYING file for license information.
 *
 * Download the latest version of phpDbEdit from
 * http://sourceforge.net/projects/phpdbedit
 * phpPgEdit from
 * http://sourceforge.net/projects/phppgedit
 * and phpMyEdit from
 * http://platon.sk/projects/phpMyEdit/
 * 
 * Some phpMyEdit to phpDbEdit conversion comments with "mrt: " prefix.
 */

/* $Platon: phpDbEdit/phpDbEditSetup.php,v 0.56 2007-05-02 23:30:00 dotmrt Exp $ */



?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
            "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>phpDbEdit Setup</title>
	<style type="text/css">
	<!--
		body  { font-family: "Verdana", "Arial", "Sans-Serif"; text-align: left }
		h1    { color: #004d9c; font-size: 13pt; font-weight: bold }
		h2    { color: #004d9c; font-size: 11pt; font-weight: bold }
		h3    { color: #004d9c; font-size: 11pt; }
		p     { color: #004d9c; font-size: 9pt; }
		table { border: 1px solid #004d9c; border-collapse: collapse; border-spacing: 0px; }
		td    { border: 1px solid; padding: 3px; color: #004d9c; font-size: 9pt; }
		hr
		{
		height: 1px;
		background-color: #000000;
		color: #000000;
		border: solid #000000 0;
		padding: 0;
		margin: 0;
		border-top-width: 1px;
		}
	-->
	</style>
</head>
<body bgcolor="white">

<?php

if (! defined('PHP_EOL')) {
	define('PHP_EOL', strtoupper(substr(PHP_OS, 0, 3) == 'WIN') ? "\r\n"
			: strtoupper(substr(PHP_OS, 0, 3) == 'MAC') ? "\r" : "\n");
}

$ty = @$_POST['ty'];
$hn = @$_POST['hn'];
$un = @$_POST['un'];
$pw = @$_POST['pw'];
if(strlen($_POST['db'])>0) $db = @$_POST['db'];
if(strlen($_POST['tb'])>0) $tb = @$_POST['tb'];
$id = @$_POST['id'];
$submit        = @$_POST['submit'];
$options       = @$_POST['options'];
$baseFilename  = @$_POST['baseFilename'];
$pageTitle     = @$_POST['pageTitle'];
$pageHeader    = @$_POST['pageHeader'];
$HTMLissues    = @$_POST['HTMLissues'];
$CSSstylesheet = @$_POST['CSSstylesheet'];

$phpExtension = '.php';
if (isset($baseFilename) && $baseFilename != '') {
	$phpFile = $baseFilename.$phpExtension;
	//$contentFile = $baseFilename.'Content.inc';
	$contentFile = $baseFilename.'.php';
} elseif (isset($tb)) {
	$phpFile = $tb.$phpExtension;
	//$contentFile = $tb.'Content.inc';
	$contentFile = $tb.'.php';
} else {
	$phpFile = 'index'.$phpExtension;
	//$contentFile = 'Content.inc';
	$contentFile = 'phpMyEdit-content.php';
}

$buffer = '';

function echo_html($x)
{
	echo htmlspecialchars($x),PHP_EOL;
}

function echo_buffer($x)
{
	global $buffer;
	$buffer .= $x.PHP_EOL;
}

#:#####################################:#
#:#  Function:   check_constraints    #:#
#:#  Parameters: tb=table name        #:#
#:#              fd=field name        #:#
#:#  return:     lookup default for   #:#
#:#              said constraint      #:#
#:#              or null if no        #:#
#:#              constraint is found. #:#
#:#  Contributed by Wade Ryan,        #:#
#:#                 20060906          #:#
#:#####################################:#
function check_constraints($tb,$fd)
{
  $query    = "show create table $tb";
  $result   = mysql_query($query);
  $tableDef = preg_split('/\n/',mysql_result($result,0,1));

  $constraint_arg="";
  while (list($key,$val) = each($tableDef)) {
    $words=preg_split("/[\s'`()]+/", $val);
    if ($words[1] == "CONSTRAINT" && $words[6]=="REFERENCES") {
      if ($words[5]==$fd) {
        $constraint_arg="  'values' => array(\n".
                        "    'table'  => '$words[7]',\n".
                        "    'column' => '$words[8]'\n".
                        "  ),\n";
      }

    }
  }
  return $constraint_arg;
}

function get_versions()
{
	$ret_ar  = array();
	$dirname = dirname(__FILE__);
	foreach (array(
				'current' => __FILE__,
				'setup'   => "$dirname/phpMyEditSetup.php",
				'core'    => "$dirname/phpMyEdit.class.php",
				'version' => "$dirname/doc/VERSION")
			as $type => $file) {
		if (@file_exists($file) && @is_readable($file)) {
			if (($f = fopen($file, 'r')) == false) {
				continue;
			}
			$str = trim(fread($f, 4096));
			if (strpos($str, ' ') === false && strlen($str) < 10) {
				$ret_ar[$type] = $str;
			} else if (preg_match('|\$'.'Platon:\s+\S+,v\s+(\d+.\d+)\s+|', $str, $matches)) {
				$ret_ar[$type] = $matches[1];
			}
			fclose($f);
		}
	}
	return $ret_ar;
}


$self = basename($_SERVER['PHP_SELF']);

//mrt $dbl  = @mysql_pconnect($hn, $un, $pw);
require_once "MDB2.php";

// mrt: different dsn-s for getting the list of databases
if (!empty($db)){
	$dsn = "$ty://$un:$pw@$hn/$db";
	$dbl =& MDB2::singleton($dsn);
} elseif (empty($db) and $ty == 'pgsql') {
	$dsn = "$ty://$un:$pw@$hn/postgres";
	$dbl =& MDB2::singleton($dsn);
} elseif (empty($db) and ($ty == 'mysql' or $ty == 'mysqli')) {
	$dsn = "$ty://$un:$pw@$hn/mysql";
	$dbl =& MDB2::singleton($dsn);
}

if ((!$dbl) or empty($submit)) {
	echo '<h1>Please log in to your database</h1>';
	if (!empty($submit)) {
		if (empty($ty)) {
			echo '<h2>Please specify the DBMS</h2>'.PHP_EOL;
		} elseif(empty($un)) {
			echo '<h2>Please specify username</h2>'.PHP_EOL;
		} elseif (empty($pw)) {
			echo '<h2>Please specify password</h2>'.PHP_EOL;
		} else {
			echo '<h2>Sorry - login failed - please try again</h2>'.PHP_EOL;			
		}
	}
	if (! isset($hn)) {
		$hn = 'localhost';
	}
	echo '
		<form action="'.htmlspecialchars($self).'" method="POST">
		<table border="1" cellpadding="1" cellspacing="0" summary="Login form">
		<tr>
		<td>DBMS*</td>
		<td><select name="ty">
			<option value="pgsql">Postgres</option>
			<option value="mysql">MySQL</option>
		</select></td>
		</tr><tr>
		<td>Hostname*</td>
		<td><input type="text" name="hn" value="'.htmlspecialchars($hn).'"></td>
		</tr><tr>
		<td>Username*</td>
		<td><input type="text" name="un" value="'.htmlspecialchars($un).'"></td>
		</tr><tr>
		<td>Password*</td>
		<td><input type="password" name="pw" value="'.htmlspecialchars($pw).'"></td>
		</tr><tr>
		<td>Database</td>
        <td><input type="text" name="db" value="'.htmlspecialchars($db).'"></td>
		</tr><tr>
		<td>Schema.Table</td>
		<td><input type="text" name="tb" value="'.htmlspecialchars($tb).'"></td>
		</tr><tr>
		<td></td>
		<td>* required</td>
		</tr>
		</table><br />
		<input type="submit" name="submit" value="Submit">
		</form>'.PHP_EOL;
} else if (empty($db)) {
	// mrt: must use MDB2 Manager module because Information_Schema implementations don't have the capability
	$dbl->loadModule('Manager');
	$dbs = $dbl->listDatabases();
	echo '<h1>Please select a database</h1>
		<form action="'.htmlspecialchars($self).'" method="POST">
		<input type="hidden" name="hn" value="'.htmlspecialchars($hn).'">
		<input type="hidden" name="un" value="'.htmlspecialchars($un).'">
		<input type="hidden" name="pw" value="'.htmlspecialchars($pw).'">
		<input type="hidden" name="ty" value="'.htmlspecialchars($ty).'">
		<table border="1" cellpadding="1" cellspacing="1" summary="Database selection">'.PHP_EOL;
	for ($i = 0; $i<count($dbs); $i++) {
		$checked =  ($i == 0 ? ' checked' : '');
		$db = htmlspecialchars($dbs[$i]);
		echo '<tr><td><input'.$checked.' type="radio" name="db" value="'.$db.'"></td><td>'.$db.'</td></tr>'.PHP_EOL;
	}
	echo '</table><br>
		<input type="submit" name="submit" value="Submit">
		<input type="submit" name="cancel" value="Cancel">
		</form>'.PHP_EOL;
} else if (!isset($tb)) {
	echo '<h1>Please select a table from database: '.htmlspecialchars($db).'</h1>
		<form action="'.htmlspecialchars($self).'" method="POST">
		<input type="hidden" name="hn" value="'.htmlspecialchars($hn).'">
		<input type="hidden" name="un" value="'.htmlspecialchars($un).'">
		<input type="hidden" name="pw" value="'.htmlspecialchars($pw).'">
		<input type="hidden" name="db" value="'.htmlspecialchars($db).'">
		<input type="hidden" name="ty" value="'.htmlspecialchars($ty).'">
		<table border="1" cellpadding="1" cellspacing="1" summary="Table selection">'.PHP_EOL;
	$tbs =& $dbl->query("select table_schema, table_name from information_schema.tables where table_type='BASE TABLE'");
	
	//$j=0;
	//$num_tbs = $dbl->@mysql_num_rows($tbs);
	for ($j = 0; $r =  $tbs->fetchRow(); $j++) {
	//while ($r = $tbs->fetchRow()) {
		$tb = htmlspecialchars($r[0].".".$r[1]);
		$checked = $j == 0 ? ' checked' : '';
		//$j++;
		echo '<tr><td><input'.$checked.' type="radio" name="tb" value="'.$tb.'"></td><td>'.$tb.'</td></tr>'.PHP_EOL;
	}
	echo '</table><br>
		<input type="submit" name="submit" value="Submit">
		<input type="submit" name="cancel" value="Cancel">
		</form>'.PHP_EOL;

} else if (!isset($id)) {
	echo '  <h1>Please select an identifier from table: '.htmlspecialchars($tb).'</h1>
		<p>
		This field will be used in change, view, copy and delete operations.<br>
		The field should be numeric and must uniquely identify a record.
		</p>
		<p>
		Please note, that there were problems reported by users regarding using
				reserved word as unique key name (the example for
				this is "key" name). Thus we recommend you to use another name
		of unique key. Usage of "id" or "ID" should be safe and good idea.
		</p>
		<form action="'.htmlspecialchars($self).'" method="POST">
		<input type="hidden" name="hn" value="'.htmlspecialchars($hn).'">
		<input type="hidden" name="un" value="'.htmlspecialchars($un).'">
		<input type="hidden" name="pw" value="'.htmlspecialchars($pw).'">
		<input type="hidden" name="db" value="'.htmlspecialchars($db).'">
		<input type="hidden" name="tb" value="'.htmlspecialchars($tb).'">
		<input type="hidden" name="ty" value="'.htmlspecialchars($ty).'">
		<table border="1" cellpadding="1" cellspacing="1" summary="Key selection">'.PHP_EOL;

	// mrt: problematic MDB2 Reverse module tableInfo
	//$dbl->loadModule('Reverse',null,true);
	//$tabinf = $dbl->tableInfo('customer');//substr($tb,stripos($tb,".")+1,strlen($tb)));
	//echo implode("<br />", $tabinf);
	if (PEAR::isError($tabinf)) {
		echo $tabinf->getMessage();
		echo $tabinf->getUserInfo();
	}
	print_r($tabinf);
	//var_dump($tabinf);
	
	$q = "SELECT cols.COLUMN_NAME, cols.data_type, cols.character_maximum_length";
	$q .= ", cols.numeric_precision, cols.numeric_scale";
	$q .= ", cols.TABLE_SCHEMA, cols.TABLE_NAME, cols.ordinal_position, tc.CONSTRAINT_TYPE";
	$q .= " FROM INFORMATION_SCHEMA.COLUMNS cols";
	$q .= " LEFT OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu ON";
	if ($ty != 'mysql' and $ty != 'mysqli') { $q .= " cols.TABLE_CATALOG = kcu.TABLE_CATALOG AND"; }
	$q .= " cols.TABLE_SCHEMA  = kcu.TABLE_SCHEMA AND";
	$q .= " cols.TABLE_NAME    = kcu.TABLE_NAME AND";
	$q .= " cols.COLUMN_NAME   = kcu.COLUMN_NAME";
	$q .= " LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc ON";
	if ($ty != 'mysql' and $ty != 'mysqli') { $q .= " kcu.TABLE_CATALOG = tc.TABLE_CATALOG AND"; }
	$q .= " kcu.TABLE_SCHEMA  = tc.TABLE_SCHEMA AND";
	$q .= " kcu.TABLE_NAME    = tc.TABLE_NAME";
	$q .= " WHERE cols.TABLE_NAME ='".substr($tb,stripos($tb,".")+1,strlen($tb))."'";
	$q .= " AND cols.TABLE_SCHEMA ='".substr($tb,0,stripos($tb,"."))."'";
	if ($ty != 'mysql' and $ty != 'mysqli') { $q .= " AND cols.TABLE_CATALOG ='".$db."'"; }
	    
	$fds = $dbl->query($q);
	//("select column_name, data_type, character_maximum_length, numeric_precision, numeric_scale " .
		//	"from information_schema.columns where table_name='".substr($tb,stripos($tb,".")+1,strlen($tb))."' " .
			//		"and table_schema='".substr($tb,0,stripos($tb,"."))."'"); 
	for ($j = 0; $fd = $fds->fetchRow(); $j++) {
	//for ($j = 0; $j < count($tabinf); $j++) {
		$ff = $fd[8];
		//$ft = $tabinf[$j]["type"];
		$ft = $fd[1].(!empty($fd[2]) ? "(".$fd[2].")" : (!empty($fd[3]) ? "(".$fd[3].",".$fd[4].")" : ""));
		//$fd = $tabinf[$j]["name"];
		$fn = $fd[0];
		//strlen($ff) <= 0 && $ff = '---';
		$checked = ($j==0) ? ' checked' : '';
		echo '<tr><td><input',$checked,' type="radio" name="id" value="',htmlspecialchars($fd[0]),'"></td>';
		echo '<td>',htmlspecialchars($fn),'</td>';
		echo '<td>',htmlspecialchars($ft),'</td>';
		echo '<td>',htmlspecialchars($ff),'</td></tr>';
	}
	echo '</table><br>
		<input type="submit" name="submit" value="Submit">
		<input type="submit" name="cancel" value="Cancel">
		</form>'.PHP_EOL;

} else if (!isset($options)) {
	echo '<h1>Please select additional options</h1>
		<form action="'.htmlspecialchars($self).'" method="POST">
		<input type="hidden" name="hn" value="'.htmlspecialchars($hn).'">
		<input type="hidden" name="un" value="'.htmlspecialchars($un).'">
		<input type="hidden" name="pw" value="'.htmlspecialchars($pw).'">
		<input type="hidden" name="db" value="'.htmlspecialchars($db).'">
		<input type="hidden" name="tb" value="'.htmlspecialchars($tb).'">
		<input type="hidden" name="ty" value="'.htmlspecialchars($ty).'">
		<input type="hidden" name="id" value="'.htmlspecialchars($id).'">
		<table border="1" cellpadding="1" cellspacing="1" summary="Additional options">
		<tr><td>Base filename</td><td><input type="text" name=baseFilename value ="'.htmlspecialchars(substr($tb,stripos($tb,".")+1,strlen($tb))).'"></td></tr>
		<tr><td>Page title</td><td><input type="text" name=pageTitle value ="'.htmlspecialchars(substr($tb,stripos($tb,".")+1,strlen($tb))).'"></td></tr>
		<tr><td>Page header</td><td><input type="checkbox" name=pageHeader></td></tr>
		<tr><td>HTML header &amp; footer</td><td><input type="checkbox" name=HTMLissues></td></tr>
		<tr><td>CSS basic stylesheet</td><td><input checked type="checkbox" name=CSSstylesheet></td></tr>
		</table><br>
		<input type="submit" name="submit" value="Submit">
		<input type="submit" name="cancel" value="Cancel">
		<input type="hidden" name="options" value="1">
		</form>'.PHP_EOL;
} else {
	echo '<h1>Here is your phpDbEdit calling program</h1>'.PHP_EOL;
	echo '<h2>You may now copy and paste it into your PHP editor</h2>'.PHP_EOL;
	if ($pageHeader) {
		echo_buffer('<h3>'.$pageTitle.'</h3>');
	}
	$versions    = '';
	$versions_ar = get_versions();
	foreach (array(
				'version' => 'phpDbEdit version:',
				'core'    => 'phpDbEdit.class.php core class:',
				'setup'   => 'phpDbEditSetup.php script:',
				'current' => 'generating setup script:')
			as $type => $desc) {
		$version = isset($versions_ar[$type]) ? $versions_ar[$type] : 'unknown';
		$versions .= sprintf("\n *  %36s %s", $desc, $version);
	}
	echo_buffer("<?php

/*
 * IMPORTANT NOTE: This generated file contains only a subset of huge amount
 * of options that can be used with phpDbEdit. To get information about all
 * features offered by phpDbEdit, check official documentation. It is available
 * online and also for download on phpMyEdit project management page:
 *
 * http://platon.sk/projects/main_page.php?project_id=5
 *
 * This file was generated by:
 *$versions
 */

// DBMS host name, user name, password, database, and table
\$opts['ty'] = '$ty';
\$opts['hn'] = '$hn';
\$opts['un'] = '$un';
\$opts['pw'] = '$pw';
\$opts['db'] = '$db';
\$opts['tb'] = '$tb';

// Name of field which is the unique key
\$opts['key'] = '$id';

");

// mrt: I do the same type query in one go a bit below
//
//	if ($id == '') {
//		echo_buffer("\$opts['key_type'] = '';");
//	} else {
//		// mrt: query from INFORMATION_SCHEMA.COLUMNS for the chosen key column datatype.
//		$fds = $dbl->query("select data_type from information_schema.columns where table_name='".substr($tb,stripos($tb,".")+1,strlen($tb))."' and table_schema='".substr($tb,0,stripos($tb,"."))."' and column_name='".$id."'"); 
//		//for ($j = 0; $fd = $fds->fetchRow(); $j++) {
//		if ($fds->numRows() == 1) {
//			$def = $fds->fetchRow();
//			echo_buffer("\$opts['key_type'] = '".$def[0]."';");
//		} 
//					
//		// mrt: MDB2 reverse module seems to have some problems with schema names
//		//$dbl->loadModule('Reverse',null,true);
//		//$def = $dbl->getTableFieldDefinition($tb,$id);
//		
//		//echo_buffer("\$opts['key_type'] = '".$def[0]["mdb2type"]."';");
//	}

	echo_buffer("
// Sorting field(s)
\$opts['sort_field'] = array('$id');

// Number of records to display on the screen
// Value of -1 lists all records in a table
\$opts['inc'] = 15;

// Options you wish to give the users
// A - add,  C - change, P - copy, V - view, D - delete,
// F - filter, I - initial sort suppressed
\$opts['options'] = 'ACPVDF';

// Number of lines to display on multiple selection filters
\$opts['multiple'] = '4';

// Navigation style: B - buttons, T - text links, G - graphic links (default)
// Buttons position: U - up, D - down (default)
\$opts['navigation'] = 'DG';

// Display special page elements
\$opts['display'] = array(
	'form'  => true,
	'query' => true,
	'sort'  => true,
	'time'  => true,
	'tabs'  => true
);

// Set default prefixes for variables
\$opts['js']['prefix']               = 'PME_js_';
\$opts['dhtml']['prefix']            = 'PME_dhtml_';
\$opts['cgi']['prefix']['operation'] = 'PME_op_';
\$opts['cgi']['prefix']['sys']       = 'PME_sys_';
\$opts['cgi']['prefix']['data']      = 'PME_data_';

/* Get the user's default language and use it if possible or you can
   specify particular one you want to use. Refer to official documentation
   for list of available languages. */
\$opts['language'] = \$_SERVER['HTTP_ACCEPT_LANGUAGE'];

/* Table-level filter capability. If set, it is included in the WHERE clause
   of any generated SELECT statement in SQL query. This gives you ability to
   work only with subset of data from table.

\$opts['filters'] = \"column1 like '%11%' AND column2<17\";
\$opts['filters'] = \"section_id = 9\";
\$opts['filters'] = \"PMEtable0.sessions_count > 200\";
*/

/* Field definitions
   
Fields will be displayed left to right on the screen in the order in which they
appear in generated list. Here are some most used field options documented.

['name'] is the title used for column headings, etc.;
['maxlen'] maximum length to display add/edit/search input boxes
['trimlen'] maximum length of string content to display in row listing
['width'] is an optional display width specification for the column
          e.g.  ['width'] = '100px';
['mask'] a string that is used by sprintf() to format field output
['sort'] true or false; means the users may sort the display on this column
['strip_tags'] true or false; whether to strip tags from content
['nowrap'] true or false; whether this field should get a NOWRAP
['select'] T - text, N - numeric, D - drop-down, M - multiple selection
['options'] optional parameter to control whether a field is displayed
  L - list, F - filter, A - add, C - change, P - copy, D - delete, V - view
            Another flags are:
            R - indicates that a field is read only
            W - indicates that a field is a password field
            H - indicates that a field is to be hidden and marked as hidden
['URL'] is used to make a field 'clickable' in the display
        e.g.: 'mailto:\$value', 'http://\$value' or '\$page?stuff';
['URLtarget']  HTML target link specification (for example: _blank)
['textarea']['rows'] and/or ['textarea']['cols']
  specifies a textarea is to be used to give multi-line input
  e.g. ['textarea']['rows'] = 5; ['textarea']['cols'] = 10
['values'] restricts user input to the specified constants,
           e.g. ['values'] = array('A','B','C') or ['values'] = range(1,99)
['values']['table'] and ['values']['column'] restricts user input
  to the values found in the specified column of another table
['values']['description'] = 'desc_column'
  The optional ['values']['description'] field allows the value(s) displayed
  to the user to be different to those in the ['values']['column'] field.
  This is useful for giving more meaning to column values. Multiple
  descriptions fields are also possible. Check documentation for this.
*/
");

	// mrt: query the INFORMATION_SCHEMA to get the column name,
	// default value, data type, constraint type and other info needed.
	// MySQL doesn't use TABLE_CATALOG value because it has no schemas, 
	// so they have the database name in the table_schema column.
	$q = "SELECT";
	$q .= " cols.TABLE_SCHEMA";
	$q .= ", cols.TABLE_NAME";
	$q .= " , cols.ordinal_position";
	$q .= " , tc.CONSTRAINT_TYPE";
	$q .= " , cols.COLUMN_NAME";
	$q .= " , cols.column_default";
	$q .= " , cols.data_type";
	$q .= " , cols.character_maximum_length";
	$q .= " , cols.numeric_precision";
	$q .= " , cols.numeric_scale";
	if ($ty != 'mysql' and $ty != 'mysqli') { $q .= "  , cols.TABLE_CATALOG"; }
	$q .= " FROM INFORMATION_SCHEMA.COLUMNS cols ";
	$q .= " LEFT OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu ON";
	if ($ty != 'mysql' and $ty != 'mysqli') { $q .= " cols.TABLE_CATALOG = kcu.TABLE_CATALOG AND"; }
	$q .= " cols.TABLE_SCHEMA  = kcu.TABLE_SCHEMA AND";
	$q .= " cols.TABLE_NAME    = kcu.TABLE_NAME AND";
	$q .= " cols.COLUMN_NAME   = kcu.COLUMN_NAME";
	$q .= " LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc ON";
	if ($ty != 'mysql' and $ty != 'mysqli') { $q .= " kcu.TABLE_CATALOG = tc.TABLE_CATALOG AND"; }
	$q .= " kcu.TABLE_SCHEMA  = tc.TABLE_SCHEMA AND";
	$q .= " kcu.TABLE_NAME    = tc.TABLE_NAME";
	$q .= " WHERE cols.table_schema='".substr($tb,0,stripos($tb,"."))."' ";
	$q .= " AND cols.table_name='".substr($tb,stripos($tb,".")+1,strlen($tb))."' ";
	if ($ty != 'mysql' and $ty != 'mysqli') { $q .= " AND cols.table_catalog='".$db."' "; }
	
	$res = $dbl->query($q);
	for ($k = 0; $see = $res->fetchRow(); $k++) {
		
		$vard = strpos($see[3],"PRIMARY");
		if ($id == '') {
			echo_buffer("\$opts['key_type'] = '';");
		} else {
			//if (!is_bool($vard)) {
			if ($see[4] == $id) {
				echo_buffer("
// Type of key field (int/real/string/date etc.)");
				echo_buffer("\$opts['key_type'] = '".$see[6]."';
");
			}
		}
		
		$fd = $see[4];
		$fn = strtr($fd, '_-.', '   ');
		$fn = preg_replace('/(^| +)id( +|$)/', '\\1ID\\2', $fn); // uppercase IDs
		$fn = ucfirst($fn);
		echo_buffer('$opts[\'fdd\'][\''.$fd.'\'] = array('); // välja nimi
		echo_buffer("  'name'     => '".str_replace('\'','\\\'',$fn)."',"); //stringitöödeldud nimi
		if ($see[6] == "set" and ($ty = 'mysql' or $ty = 'mysqli')) {
			echo_buffer("  'select'   => 'M',");
		} else {
			echo_buffer("  'select'   => 'T',");
		}
		
		// primary key columns read only
		if (!is_bool($vard)) {
			echo_buffer("  'options'  => 'AVCPDR', // primary key kolumn");
		}

		// mrt: to extract column length into opts array "maxlen"
		if (!empty($see[7])) {
			echo_buffer("  'maxlen'   => ".$see[7].",");
		} elseif (!empty($see[8])) {
			echo_buffer("  'maxlen'   => ".$see[8].",");
		}

		// blobs -> textarea
		if ($see[6] == 'blob') {
			echo_buffer("  'textarea' => array(");
			echo_buffer("    'rows' => 5,");
			echo_buffer("    'cols' => 50),");
		}

		// SETs and ENUMs get special treatment
		// mrt: phpMyEdit extracts the enum values automatically, but this is broken here.
		if (($see[6] == 'set' || $see[6] == 'enum') and ($ty = 'mysql' or $ty = 'mysqli')) {
			echo_buffer("  'values'   => array(\"val1\",\"val2\", ...), // ENTER ENUM/SET VALUES HERE");
		}

		// automatic support for Default values. Primary key was in phpMyEdis default => 0
		if (!is_null($see[5]) && $see[5] !== "") {
			echo_buffer("  'default'  => '".str_replace('\'','\\\'',$see[5])."',");
		} elseif (!is_bool($vard)) {
			echo_buffer("  'default'  => '0',");
		}

		echo_buffer("  'sort'     => true");
		echo_buffer(');');
	}
	
	echo_buffer("
// Now important call to phpDbEdit
require_once 'phpDbEdit.class.php';
new phpDbEdit(\$opts);

?>
");

	$css_directive = <<<END
<style type="text/css">
	hr.pme-hr		     { border: 0px solid; padding: 0px; margin: 0px; border-top-width: 1px; height: 1px; }
	table.pme-main 	     { border: #004d9c 1px solid; border-collapse: collapse; border-spacing: 0px; width: 100%; }
	table.pme-navigation { border: #004d9c 0px solid; border-collapse: collapse; border-spacing: 0px; width: 100%; }
	th.pme-header	     { border: #004d9c 1px solid; padding: 4px; background: #add8e6; }
	td.pme-key-0, td.pme-value-0, td.pme-help-0, td.pme-navigation-0, td.pme-cell-0,
	td.pme-key-1, td.pme-value-1, td.pme-help-0, td.pme-navigation-1, td.pme-cell-1,
	td.pme-sortinfo, td.pme-filter { border: #004d9c 1px solid; padding: 3px; }
	td.pme-buttons { text-align: left;   }
	td.pme-message { text-align: center; }
	td.pme-stats   { text-align: right;  }
</style>
END;
	if (! $CSSstylesheet) {
		$css_directive = '';
	}

	if ($HTMLissues) {
		$buffer = <<<END
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
		"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>$pageTitle</title>
$css_directive
</head>
<body>
$buffer
</body>
</html>
END;
	} else if ($CSSstylesheet) {
		$buffer = $css_directive . $buffer;
	}
	// write the content include file
	echo 'Trying to write content file to: <b>'.'./'.$contentFile.'</b><br>'.PHP_EOL;
	$filehandle = @fopen('./'.$contentFile, 'w+');
	if ($filehandle) {
		fwrite($filehandle, $buffer);
		flush($filehandle);
		fclose($filehandle);
		echo 'phpMyEdit content file written successfully<br>';
	} else {
		echo 'phpMyEdit content file was NOT written due to inssufficient privileges.<br>';
		echo 'Please copy and paste content listed below to <i>'.'./'.$contentFile.'</i> file.';
	}
	echo '<br><hr>';
	echo '<pre>';
	echo_html($buffer);
	echo '</pre><hr>'.PHP_EOL;
}

?>

</body>
</html>

Return current item: PhpDbEdit