<?php

	session_start();

	if ($_POST['password'] != "plastic" && val( $_SESSION, 'sql_window_password' ) != "plastic")
		exit();

	$_SESSION['sql_window_password'] = "plastic";

	echo "<html><head><title>SQL Query Sender</title></head><body>";

	if (ini_get("magic_quotes_gpc") == "1")
	{
		$_POST['query'] = stripslashes($_POST['query']);
	}

	if (val( $_POST, "live_update" ) != "on" &&
		val( $_GET, "db" ) == "academi1_monashconnect" &&
		(strpos( $_POST['query'], "delete" ) !== false ||
		strpos( $_POST['query'], "insert" ) !== false ||
		strpos( $_POST['query'], "update" ) !== false))
	{
		echo "Live update attempted on production";
		exit();
	}

	$host="localhost";
	$user="academi1_mlm1";
	$password="plastic1";

	$cxn = mysql_connect($host,$user,$password);

	mysql_select_db ("academi1_monashconnect");

//	mysql_select_db ($_GET['db']);

	$query = $_POST['query'];

	$query = str_replace( "counx", "count", $query);

	$result = mysql_query($query, $cxn);

	$rows = mysql_affected_rows( $cxn );

//	echo "Database: ".$_GET['db']."<br><br>";

	if($result == false)
	{
		echo "<h4>Error: ".mysql_error($cxn)."</h4>";
	}
	elseif(@mysql_num_rows($result) == 0)
	{
		echo "<h4>Query completed. No results returned.<br><br>";

		echo $rows." rows affected.</h4>";
	}
	else
	{
		if (val( $_POST, "table_layout" ) == "on")
		{
			echo "<table border='0'><tr>";

			for ($j=0; $j < mysql_num_fields($result); $j++)
					echo "<td><b>".mysql_field_name($result,$j)."</b></td>";

			echo "</tr>";

			for ($i=0;$i < mysql_num_rows($result);$i++)
			{
				$row = mysql_fetch_row($result);

				echo "<tr>";

				for($j=0; $j < mysql_num_fields($result); $j++)
					echo "<td>".$row[$j]."</td>";
			
				echo "</tr>";
			}

			echo "</table>";
		}
		else
		{
			echo "<table border='0'><tbody>";

			for ($i=0;$i < mysql_num_rows($result);$i++)
			{
				$row = mysql_fetch_row($result);

				for($j=0; $j < mysql_num_fields($result); $j++)
					echo "<tr><td><b>".mysql_field_name($result,$j)."</b></td><td>".$row[$j]."</td></tr>";
			
				echo "<tr><td><hr></td><td><hr></td></tr>";
			}

			echo "</tbody></table>";
		}
	}

	function val( $xarray, $variable )
	{
		if (array_key_exists( $variable, $xarray ))
			$value = $xarray[ $variable ];
		else
			$value = "";

		return ($value);
	}
	
?>
