<?php

	// every page that uses this shared file automatically connects to the editor's database
	db_connect_editor();


	// but we may need to connect to another database for content storage
	function db_connect_editor() {
		db_connect(DB_HOSTNAME, DB_NAME, DB_USERNAME, DB_PASSWORD);
	}
	function db_connect_content() {
		db_connect(DATABASE_HOST, DATABASE_NAME, DATABASE_USERNAME, DATABASE_PASSWORD);
	}

	
	function db_connect($host, $name, $username, $password) {
		GLOBAL $db_connected, $db_selected;
		$db_connected = @mysql_connect($host, $username, $password) or ($host) ? db_show_error("Could not connect to database at \"".$host."\".") : "" ;
		if ($db_connected) {
			$db_selected = @mysql_select_db($name) or ($name) ? db_show_error("Could not select database \"".$name."\".") : "" ;
		} else {
			$db_selected = FALSE;
		}
	}


	function db_switch($db_name) {
		// changes the database we're connected to
		$result = mysql_select_db($db_name);
		return $result;
	}


	function db_do_query($query) {
		// passes an SQL query to the database and returns the result, and prints the error if there is one
		
		// if we're in demo mode, don't do UPDATE, INSERT or DELETE queries
		if ($GLOBALS["demo"]) {
			$query_type = preg_replace("/^\s*(\w+).*$/s", "$1", $query);
			if (in_array($query_type, array("UPDATE", "INSERT", "DELETE"))) {
				return 1;
			}
		}
		
		$result = mysql_query($query);
		if (!$result) {
			$error = mysql_error();
			db_show_error($error, $query);
		}
		return $result;
	}
	
	
	function db_get_insert_ID($result) {
		// returns the ID of a newly inserted row
		$insert_ID = mysql_insert_id();
		return $insert_ID;
	}
	
	
	function db_get_row($result, $index) {
		// returns the requested row in the form of an associative array
		// rather than blocking the errors here, it would be nice to check if the row exists and return "" if not
		@mysql_data_seek($result, $index);
		$row = mysql_fetch_assoc($result); // this is the same as using mysql_fetch_array with the MYSQL_ASSOC argument, but a bit faster; note that neither allows you to access results by index, only by name; you need mysql_fetch_array with MYSQL_BOTH to do that
		return $row;
	}
	
	
	function db_num_rows($result) {
		// returns the number of rows in a given query result
		$num = ($result != 0) ? mysql_numrows($result) : 0 ;
		return $num;
	}
	

	function db_affected_rows($result) {
		// returns the number of rows in a given query result
		$num = mysql_affected_rows();
		return $num;
	}
	
	
	function db_show_error($error, $query="") {
		if (SHOW_ERRORS) {
			print "<p class=\"feedback-negative\">Error: $error</p>";
			if ($query) {
				print "<p class=\"debug\">$query</p>";
			}
		} else {
			print "<p class=\"feedback-negative\">A database error occurred. Please see the error log for details.</p>";
			error_log($error);
			if ($query) {
				error_log($query);
			}
		}
	}

?>
