execute it, else display the headers */ if (isset($submit_sql) && eregi('^SELECT', $encoded_sql_query)) { $goto = 'db_details.php3'; $zero_rows = htmlspecialchars($strSuccess); $sql_query = urldecode($encoded_sql_query); if (get_magic_quotes_gpc()) { $sql_query = addslashes($sql_query); } include('./sql.php3'); exit(); } else { $sub_part = '_qbe'; include('./db_details_common.php3'); $url_query .= '&goto=db_details_qbe.php3'; include('./db_details_db_info.php3'); } if (isset($submit_sql) && !eregi('^SELECT', $encoded_sql_query)) { echo '

' . $strHaveToShow . '

'; } /** * Initialize some variables */ if (empty($Columns)) { $Columns = 3; // Initial number of columns } if (!isset($Add_Col)) { $Add_Col = ''; } if (!isset($Add_Row)) { $Add_Row = ''; } if (!isset($Rows)) { $Rows = ''; } if (!isset($InsCol)) { $InsCol = ''; } if (!isset($DelCol)) { $DelCol = ''; } if (!isset($prev_Criteria)) { $prev_Criteria = ''; } // workaround for a PHP3 problem if (!isset($Criteria)) { //$Criteria = ''; $Criteria = array(); for ($i = 0; $i < $Columns; $i++) { $Criteria[$i] = ''; } } if (!isset($InsRow)) { // $InsRow = ''; $InsRow = array(); for ($i = 0; $i < $Columns; $i++) { $InsRow[$i] = ''; } } if (!isset($DelRow)) { // $DelRow = ''; $DelRow = array(); for ($i = 0; $i < $Columns; $i++) { $DelRow[$i] = ''; } } if (!isset($AndOrRow)) { // $AndOrRow = ''; $AndOrRow = array(); for ($i = 0; $i < $Columns; $i++) { $AndOrRow[$i] = ''; } } if (!isset($AndOrCol)) { // $AndOrCol = ''; $AndOrCol = array(); for ($i = 0; $i < $Columns; $i++) { $AndOrCol[$i] = ''; } } // minimum width $wid = 12; $col = $Columns + $Add_Col; if ($col < 0) { $col = 0; } $row = $Rows + $Add_Row; if ($row < 0) { $row = 0; } /** * Prepares the form */ $tbl_result = PMA_mysql_list_tables($db); $tbl_result_cnt = mysql_num_rows($tbl_result); $i = 0; $k = 0; // The tables list sent by a previously submitted form if (!empty($TableList)) { for ($x = 0; $x < count($TableList); $x++) { $tbl_names[urldecode($TableList[$x])] = ' selected="selected"'; } } // end if // The tables list gets from MySQL while ($i < $tbl_result_cnt) { $tbl = PMA_mysql_tablename($tbl_result, $i); $fld_results = @PMA_mysql_list_fields($db, $tbl) or PMA_mysqlDie(PMA_mysql_error(), 'PMA_mysql_list_fields(' . $db . ', ' . $tbl . ')', FALSE, $err_url); $fld_results_cnt = ($fld_results) ? mysql_num_fields($fld_results) : 0; $j = 0; if (empty($tbl_names[$tbl]) && !empty($TableList)) { $tbl_names[$tbl] = ''; } else { $tbl_names[$tbl] = ' selected="selected"'; } // end if // The fields list per selected tables if ($tbl_names[$tbl] == ' selected="selected"') { $fld[$k++] = PMA_backquote($tbl) . '.*'; while ($j < $fld_results_cnt) { $fld[$k] = PMA_mysql_field_name($fld_results, $j); $fld[$k] = PMA_backquote($tbl) . '.' . PMA_backquote($fld[$k]); // increase the width if necessary if (strlen($fld[$k]) > $wid) { $wid = strlen($fld[$k]); } //end if $k++; $j++; } // end while } // end if if ($fld_results) { mysql_free_result($fld_results); } $i++; } // end if mysql_free_result($tbl_result); // largest width found $realwidth = $wid . 'ex'; /** * Displays the form */ ?>
 : 
 : 
 :  />
 : 
 :  : />  
 :  : />  
 :  : />
 :  : />
 :   : />    : />
  
 : />    : />
  
 :
 :
 :

";
// First we need the really needed Tables - those in TableList might
// still be all Tables.
if (isset($Field) && count($Field) > 0) {

    // Initialize some variables
    $tab_all    = array();
    $col_all    = array();
    $tab_know   = array();
    $tab_left   = array();
    $col_where  = array();
    $fromclause = '';

    //  we only start this if we have fields, otherwise it would be dumb
//echo "get everything\n";
    while (list(, $value) = each($Field)) {
        $_parts            = explode('.', $value);
        if (!empty($_parts[0]) && !empty($_parts[1])) {
        	$_tab_raw  = urldecode($_parts[0]);
            $_tab      = str_replace('`', '', $_tab_raw);
//echo "new Tab: " . $_tab . "\n";
            $tab_all[$_tab] = $_tab;
            $_col_raw  = urldecode($_parts[1]);
            $col_all[] = $_tab . '.' . str_replace('`', '', $_col_raw);
//echo "new col:" . $_tab . '.' . str_replace('`', '', $_col_raw) . "\n";
         }
    } // end while

//echo "check whereclauses\n";
    if ($cfgRelation['relwork'] && count($tab_all) > 0) {
        // now we need all tables that we have in the whereclause
        for ($x = 0; $x < count($Criteria); $x++) {
            $_tab_wher = explode('.', urldecode($Field[$x]));
            if(!empty($_tab_wher[0]) && !empty($_tab_wher[1])) {
                $_tab_raw  = urldecode($_tab_wher[0]);
                $_tab      = str_replace('`', '', $_tab_raw);

                $_col_raw  = urldecode($_tab_wher[1]);
                $_col      = str_replace('`', '', $_col_raw);
                $_col = $_tab . '.' . $_col;
                //	now we know that our array has the same numbers as $Criteria
                //	we can check which of our columns has a whereclause
                if (!empty($Criteria[$x])) {
                	if (substr($Criteria[$x],0,1) == '=' || eregi('is',$Criteria[$x])) {
                    	$col_where[$_col] = $_col;
                        $tab_where[$_tab] = $_tab;
// echo "new Whereclause:".$_tab."\n";
                    }
                }
            }
        } // end for

         //	clean temp vars w/o further use
         unset($_tab_raw,$_col_raw);


        if (count($tab_where) == 1) {
            // if there is exactly one column that has a decent where-clause
            // we will just use this
            $master = key($tab_where);
// echo "nur ein where: master =".$master . "\n";
        } else {
        	// now let's find out which of the tables has an index
// echo "prüfe indexe:\n";
			while (list(, $_tab) = each($tab_all)) {
				$ind_qry  = 'SHOW INDEX FROM ' . PMA_backquote($_tab);
                $ind_rs   = PMA_mysql_query($ind_qry);
                while ($ind = PMA_mysql_fetch_array($ind_rs)) {
                	$_col = $_tab . '.' . $ind['Column_name'];
					if (isset($col_all[$_col])) {
                        if ($ind['non_unique'] == 0) {
                            if (isset($col_where[$_col])) {
                                $col_unique[$_col] = 'Y';
                            } else {
                                $col_unique[$_col] = 'N';
                            }
//echo "neuen unique index gefunden:".$_col."\n";
                        } else {
                            if (isset($col_where[$_col])) {
                                $col_index[$_col] = 'Y';
                            } else {
                                $col_index[$_col] = 'N';
                            }
//echo "neuen index gefunden:".$_col."\n";
                        }
    				}
                }	// End while (each col of tab)
			}	//	End while (each tab)
            // now we want to find the best.
			if (isset($col_unique) && count($col_unique)>0) {
            	$col_cand = $col_unique;
// echo "Kandidaten sind jetzt alle mit unique index\n";
                $_needsort= 1;
            } elseif (isset($col_index) && count($col_index) > 0) {
            	$col_cand = $col_index;
                $_needsort= 1;
// echo "Kandidaten sind jetzt alle mit index\n";
            } elseif (isset($col_where) && count($col_where) > 0) {
            	$col_cand = $tab_where;
// echo "Kandidaten sind jetzt alle im whereclause\n";
                $_needsort= 0;
            } else {
            	$col_cand = $tab_all;
                $_needsort= 0;
// echo "Kandidaten sind jetzt alle \n";
            }
			
            //	if we came up with $col_unique (very good) or
            //	$col_index (still good) as $col_cand we want to check
            //  if we have any 'Y' there (that would mean that 
            //	they were also found in the whereclauses which would be
            //	great). if yes, we take only those
            if ($_needsort == 1) {
            	while (list($_col,$_iswhere) = each($col_cand)) {
                	$_tab = explode('.',$_col);
                    $_tab = $_tab[0];
                	if ($_iswhere == 'Y') {
                    	$_vg[$_col]  = $_tab;
                    } else {
                    	$_sg[$_col]  = $_tab;
                    }
               	}
               	if (isset($vg)) {
                	$col_cand = $vg;
// echo "Kandidaten konnten auf index+where beschränkt werden\n";
                } else {
                	$col_cand = $sg;
// echo "keiner der Kandidaten mit Index ist im wherclause\n";
                }
            }

            // if our array of candidates has more than one member
            //	we'll just find the smallest table.
            //	of course the actual query would be faster if we check 
            //	for the Criteria which gives the smallest resultset
            //  in its table, but it would take too much time to check this

            if (count($col_cand)>1) {
//echo "wir haben immer noch mehr als einen Kandidaten. Prüfe Größe\n";
            	//	of course we only want to check each table once
                $_checked_tables = $col_cand;
                while (list(, $_tab) = each($col_cand)) {
                    if ($_checked_tables[$_tab] != 1 ) {
//echo "prüfe jetzt: Tabelle ".$_tab. "\n";
                        $rows_qry = 'SELECT count(1) as anz '
                                  . 'FROM ' . PMA_backquote($_tab);
                        $rows_rs  = PMA_mysql_query($rows_qry);
                		while ($res = PMA_mysql_fetch_array($rows_rs)) {
							$_tsize[$_tab] = $res['anz'];
//echo "$_tab hat:" .$_tsize[$_tab]."\n";
                        }
                        $_checked_tables[$_tab] =1;
                    }
                    $_csize[$_tab] = $_tsize[$_tab];
//echo "erster csize: ".$_csize[$_tab]."\n";
                }
                asort($_csize);
                reset($_csize);
                $master = key($_csize);
//echo "kleinste Datei: " . $master . "\n";
            } else {
            	$master = $col_cand[0];
//echo "master ist der einzige Kandidat: " . $master . "\n";
            }
        } // end if (exactly one where clause)
//echo "ich habe mich entschieden: " . $master;
//die;

  		// i will need something to remove unwanted entries from
        // arrays which works with php3
        function array_short($array,$key)
        {
            while (list($k, $v) = each($array)) {
                if ($k != $key) {
                    $reta[$k] = $v;
                }
            }
            if(!isset($reta)){
            	$reta = array();
            }
            return $reta;
        }

        // now we will often need a function to find all
        // related tables. what we will have is an array
        // of allready connected tables $tab_know and one
        // of tables that we still couldn't connect $tab_left
        // all we start with is $tab_all and the knowledge of
        // our $master
        // as we need to work with php3 we cannot give the variables
        // by & so i need to make them global ;-(
        //	the only thing we give  is wether to go from
        // master to foreign or vice versa

        function getrelatives($from) {
        	global $tab_left,$tab_know,$fromclause,$db,$cfgRelation,$dbh;
            if ($from == 'master') {
            	$to    = 'foreign';
            } else {
            	$to    = 'master';
            }
			$in_know = '(\'' . implode('\', \'', $tab_know) . '\')';
            $in_left = '(\'' . implode('\', \'', $tab_left) . '\')';

            $rel_query = 'SELECT *'
                       . ' FROM ' . PMA_backquote($cfgRelation['relation'])
                       . ' WHERE ' . $from . '_db   = \'' . $db . '\''
                       . ' AND   ' . $to   . '_db   = \'' . $db . '\''
                       . ' AND ' . $from . '_table IN ' . $in_know
                       . ' AND ' . $to   . '_table IN ' . $in_left;
            if (isset($dbh)) {
                PMA_mysql_select_db($cfgRelation['db'], $dbh);
                $relations = @PMA_mysql_query($rel_query, $dbh) or PMA_mysqlDie(PMA_mysql_error($dbh), $rel_query, '', $err_url_0);
                PMA_mysql_select_db($db, $dbh);
            } else {
                PMA_mysql_select_db($cfgRelation['db']);
                $relations = @PMA_mysql_query($rel_query) or PMA_mysqlDie('', $rel_query, '', $err_url_0);
                PMA_mysql_select_db($db);
            }
            while ($row = PMA_mysql_fetch_array($relations)) {
                $found_table = $row[$to.'_table'];
                if (isset($tab_left[$found_table])) {
                    $fromclause .= "\n LEFT JOIN "
                        . PMA_backquote($row[$to  . '_table']) . ' ON '
                        . PMA_backquote($row[$from. '_table']) . '.'
                            . PMA_backquote($row[$from. '_field']) . ' = '
                        . PMA_backquote($row[$to  . '_table']) . '.'
                            . PMA_backquote($row[$to  . '_field']) .' ';
                    $tab_know[$found_table] = $found_table;
                    $tab_left = array_short($tab_left,$found_table);
             	}
            } // end while
		} // End of Function


        $tab_left = array_short($tab_all,$master);
        $tab_know[$master] = $master;

        $run=0;$emerg='';
		while (count($tab_left)>0) {
        	if ($run % 2 ==0) {
            	getrelatives('master');
            } else {
            	getrelatives('foreign');
            }
            $run++;
            if ($run>5) {

            	while ( list(,$_tab) = each($tab_left)) {
                	$emerg .= ', '.$_tab;
            		$tab_left=array_short($tab_left,$_tab);
                }
            }
         }
         $qry_from = $master . $emerg . $fromclause;
    }

} // end count($Field) > 0

// now let's see what we got
if (!empty($qry_from)) {
    $encoded_qry .= urlencode('FROM ' . $qry_from . "\n");
    echo  'FROM ' . htmlspecialchars($qry_from) . "\n";
}

// 3. WHERE
$qry_where          = '';
$criteria_cnt       = 0;
for ($x = 0; $x < $col; $x++) {
    if (!empty($curField[$x]) && !empty($curCriteria[$x]) && $x && isset($last_where)) {
        $qry_where  .= ' ' . strtoupper($curAndOrCol[$last_where]) . ' ';
    }
    if (!empty($curField[$x]) && !empty($curCriteria[$x])) {
        $qry_where  .= '(' . $curField[$x] . ' ' . $curCriteria[$x] . ')';
        $last_where = $x;
        $criteria_cnt++;
    }
} // end for
if ($criteria_cnt > 1) {
    $qry_where      = '(' . $qry_where . ')';
}

// OR rows ${"cur".$or}[$x]
if (!isset($curAndOrRow)) {
    $curAndOrRow          = array();
}
for ($y = 0; $y <= $row; $y++) {
    $criteria_cnt         = 0;
    $qry_orwhere          = '';
    $last_orwhere         = '';
    for ($x = 0; $x < $col; $x++) {
        if (!empty($curField[$x]) && !empty(${'curOr' . $y}[$x]) && $x) {
            $qry_orwhere  .= ' ' . strtoupper($curAndOrCol[$last_orwhere]) . ' ';
        }
        if (!empty($curField[$x]) && !empty(${'curOr' . $y}[$x])) {
            $qry_orwhere  .= '(' . $curField[$x]
                          .  ' '
                          .  (get_magic_quotes_gpc() ? stripslashes(${'curOr' . $y}[$x]) : ${'curOr' . $y}[$x])
                          .  ')';
            $last_orwhere = $x;
            $criteria_cnt++;
        }
    } // end for
    if ($criteria_cnt > 1) {
        $qry_orwhere      = '(' . $qry_orwhere . ')';
    }
    if (!empty($qry_orwhere)) {
        $qry_where .= "\n"
                   .  strtoupper(isset($curAndOrRow[$y]) ? $curAndOrRow[$y] . ' ' : '')
                   .  $qry_orwhere;
    } // end if
} // end for

if (!empty($qry_where) && $qry_where != '()') {
    $encoded_qry .= urlencode('WHERE ' . $qry_where . "\n");
    echo 'WHERE ' . htmlspecialchars($qry_where) . "\n";
} // end if

// 4. ORDER BY
$last_orderby = 0;
if (!isset($qry_orderby)) {
    $qry_orderby      = '';
}
for ($x = 0; $x < $col; $x++) {
    if ($last_orderby && $x && !empty($curField[$x]) && !empty($curSort[$x])) {
        $qry_orderby  .=  ', ';
    }
    if (!empty($curField[$x]) && !empty($curSort[$x])) {
        // if they have chosen all fields using the * selector,
        // then sorting is not available
        // Robbat2 - Fix for Bug #570698
        if (substr($curField[$x], -2) != '.*') {
            $qry_orderby  .=  $curField[$x] . ' ' . $curSort[$x];
            $last_orderby = 1;
        }
    }
} // end for
if (!empty($qry_orderby)) {
    $encoded_qry .= urlencode('ORDER BY ' . $qry_orderby);
    echo 'ORDER BY ' . htmlspecialchars($qry_orderby) . "\n";
}
?>