<?php

function db_connect($dbname)
{
  // put db parameters into variable incase connection fails 
  // (to prevent reveling parameter values)
  $db_password = "Ninein234@#$";
  $db_user     = "zeroproc_pineapplepnp";

	try
	{
		// $db = new PDO("mysql:host=localhost;dbname=www","www","wwwWWW#@!321");
		$db = new PDO("mysql:host=localhost;dbname=$dbname",$db_user,$db_password);
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		return($db);	
	}
	catch (PDOException $e)
	{
		print "<pre>";
		//print_r("\n" . $e->getCode() . "\n");
		print_r("\n" . $e->getMessage() . "\n");
		print "\nIf message is 'could not find driver' try checking php.ini";
		//print_r("\n" . $e . "\n");
		print "</pre>";
		return($db);
	}
}

function db_get_record($db, $statement, $prepared_array)
{
  $sth = $db->prepare($statement);
  $sth->execute($prepared_array);
	$row_count = 0;
	// Only get a single row (no loop on the fetch)
  $record = $sth->fetch(PDO::FETCH_ASSOC);
  return $record;
}

function db_edit_row($db, $statement, $prepared_array, $action_form, $dropdowns)
{
	//print "<pre>";
  //print_r($statement);
	//print_r($prepared_array);
	//print "</pre>";

  //$sth = $db->query ($statement);
  $sth = $db->prepare($statement);
  $sth->execute($prepared_array);

	print<<<END
<form action="$action_form" method="post">
  <table id="t01">
		<tr>
			<th>Field</th>
			<th>Data</th>
		</tr>
END;

	$row_count = 0;
	// Only get a single row (no loop on the fetch)
  $row = $sth->fetch(PDO::FETCH_NUM);
  {
    for($i = 0; $i < $sth->columnCount(); $i++)
    {
			$row_count++;
			print("<tr>\n");
			print("<td>" . $sth->getColumnMeta($i)["name"] . "</td>\n");
			//print("<td>" . htmlspecialchars($row[$i]) . "</td>\n");
			if( array_key_exists($sth->getColumnMeta($i)["name"], $dropdowns) ){
				print("<td>");
				db_dropdown($db, $dropdowns[$sth->getColumnMeta($i)["name"]], $sth->getColumnMeta($i)["name"], array($row[$i]));
				print("</td>");
			}
			else{
				print("<td><input type=\"text\" size=\"55\" name=\"" . $sth->getColumnMeta($i)["name"] . "\" value=\"" . htmlspecialchars($row[$i]) . "\"></td>");
			}
			print("</tr>\n");
    }
  }
  print("</table>\n");

	print<<<END
<input type="submit" value="Submit">
<input type="submit" name="btnDelete" value="One Click Delete, No Conformation">
</form>
END;
}

function link_by_name($link, $row, $column) {
	$get_string = "";
	if(isset($link)) {
		foreach ($link as $param=>$value) {
			if(isset($value["type"])) {
				if($value["type"] == "link") {
					if(isset($value["column"])) {
						if($value["column"] == $column) {
							if(isset($value["getparams"])) {
								foreach ($value["getparams"] as $column_name=>$get_name) {
									if(!($get_string == ""))
										$get_string = $get_string . "&";
									$get_string = $get_string . "$get_name=" . htmlspecialchars($row[$column_name]);
								}
							}
							return($value["link"] . "?" . $get_string);
						}
					}
				}
			}
		}
	}
}
function db_display_row($db, $statement, $prepared_array, $id, $link)
{
	//print "<pre>";
  //print_r($statement);
	//print_r($prepared_array);
	//print_r($link);
	//print link_by_name($link, "file_id");
	//print("\n");
	//print "</pre>";

  //$sth = $db->query ($statement);
  $sth = $db->prepare($statement);
  $sth->execute($prepared_array);

	print<<<END
  <table id="$id">
		<tr>
			<th>Field</th>
			<th>Data</th>
		</tr>
END;

	$row_count = 0;
	// Only get a single row (no loop on the fetch)
  $row = $sth->fetch(PDO::FETCH_BOTH);
  {
    for($i = 0; $i < $sth->columnCount(); $i++)
    {
			$row_count++;
			$column = $sth->getColumnMeta($i)["name"];
			$href = link_by_name($link, $row, $column);
			print("<tr>\n");
			print("<td>" . $sth->getColumnMeta($i)["name"] . "</td>\n");				
			if( isset($href) ) {
				print("<td><a href=\"$href\">" . htmlspecialchars($row[$i]) . "</a></td>");
			}
			else {
				print("<td>" . htmlspecialchars($row[$i]) . "</td>");
			}
			print("</tr>\n");
    }
  }
  print("</table>\n");
}
/***********************************************************
 db_table_prepared($db, $statement, $prepared_array, $id, $link)

 $db => handle to the database
 $statement => prepared SQL statement with ? for each prepared value
 $prepared_array => array of prepared values for the prepared statement
                    $array = array("foo", "bar", "hello", "world");
 $id => CSS table id
 $link => An array of arrays.  Each sub array corasponds to a column in the generated
          table and has two parameters.  
					1. The link address with keyword link: "link"=>"http-address"
					2. An array of GET parameters to pass to the link
							'db-column-name' => 'get-parameter'

	The following creates a link in the first column of a two column table:
	
	array(
				array("link"=>"http://www.digikey.com/product-search/en", 
							array('distributor_part_number'=>'keywords')
							),
				array("")
				)
***********************************************************/
function db_table_prepared($db, $statement, $prepared_array, $id, $link)
{	
try
{
	// debug code:
  //print("<br />$statement\n");	
	//foreach ($columns as $column) {
	//	print("<br />$column\n");
	//}

	//print "<pre>";
	//print_r("\n" . $statement . "\n");
	//print_r($link);
	//print_r($prepared_array);
	//print "</pre>";

	
  //$sth = $db->query ($statement);
	$db->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
  $sth = $db->prepare ($statement);
  $sth->execute($prepared_array);

  print("<table id=\"$id\">\n");
  print("<tr>\n"); 
  foreach(range(0, $sth->columnCount() - 1) as $column_index)
  {
    print("<th>" . $sth->getColumnMeta($column_index)["name"] . "</th>\n");
  }
  print("</tr>\n");

	$row_count = 0;
  while($row = $sth->fetch(PDO::FETCH_BOTH))
  {
		$row_count++;
		print("<tr>\n");
    for($i = 0; $i < $sth->columnCount(); $i++)
    {
			if(isset($link[$i]["link"]))
			{
				$link_str = $link[$i]["link"];
				if(!($link_str == ""))
				{
					$get_string = "";
					foreach ($link[$i][0] as $column=>$value) {
						if(!($get_string == ""))
							$get_string = $get_string . "&";
						$get_string = $get_string . "$value=" . htmlspecialchars($row[$column]);
					}
					$href = "<a href=\"$link_str?$get_string\">";
					$href_prime = "</a>";
				}
			}
			else
			{
				$href = "";
				$href_prime = "";
			}
      print("<td>$href" . htmlspecialchars($row[$i]) . "$href_prime</td>\n");
    }
    print("</tr>\n");
  }
  print("</table>\n");
}
catch (PDOException $e)
{
	print "<br />";
	print_r("\n" . $e . "\n");
	//print "</pre>";
}
}

function db_table($db, $statement, $id, $link)
{
	try
	{
		//db_table_prepared($db, $statement, $parameter_array, "#table_id", $link);
		db_table_prepared($db, $statement, NULL, $id, $link);
	}
	catch(PDOException $e)
	{
		# Print error information from exception object
		print (" getCode value: " . $e-> getCode () . "\ n");
		print (" getMessage value: " . $e-> getMessage () . "\ n");
		# Print error information from database handle
		print (" errorCode value: " . $db-> errorCode () . "\ n");
		print (" errorInfo value: " . join (",", $db-> errorInfo ()) . "\ n");

		// DuBois, Paul (2013-03-28). MySQL (5th Edition) (Developer's Library) (Kindle Locations 16308-16311). Pearson Education. Kindle Edition. 		
	}
}

function db_dropdown($db, $statement, $id, $selected_values)
{
  $sth = $db->query ($statement);

	//if(isset($_POST["$id"]))	$a = $_POST["$id"];
  //print("<pre>\n");	print_r($selected_values);  print("</pre>\n");

	print("<select name=\"{$id}[]\" multiple=\"multiple\" id=\"$id\" style=\"display: none;\">\n"); // style display none keeps raw html from rendering on page load

  while($row = $sth->fetch(PDO::FETCH_NUM)){
		$selected = "";
		if(isset($selected_values))
		{
			if(in_array($row[0], $selected_values))
			{
				$selected = " selected";
			}
		}
		print("<option value=\"" . htmlspecialchars($row[0]) . "\" $selected>" . htmlspecialchars($row[1]) . "</option>\n");
  }
  print("</select>\n");
	// DEBUG: Show the sql statement that generates this dropdown.
  //print("$statement<br />\n");
  //print("$id<br />\n");
}

function db_create_update($db, $table_name, $row)
{
	/*
			1. Query the database for the primary keys in the table specified and create a new list 
				 that is the union of the keys in the table and the keys in the $row array.
	
					$primary_keys is an array of column names that make up the primary key
	*/
	$debug = 0;
	if($debug) print "Extracting list of primary_keys for $table_name:\n";
	$statement = "SHOW KEYS FROM `$table_name` WHERE Key_name='PRIMARY'";
	$prepared_array = array();
	$sth = $db->prepare($statement);
	$sth->execute($prepared_array);

	while($db_row = $sth->fetch(PDO::FETCH_BOTH)) {
		$key = $db_row["Column_name"];
		if($debug) print("$key\n");
		if( array_key_exists ($key , $row) ) {
			$primary_keys[$key] = $row[$key];
		}	
		else {
			// Error detection
			// ===============
			// o. If the $row array does not contain necessary keys to uniquly detect a row of the table an exception should be thrown
			$error = 'primary key missing from $row data';
			throw new Exception($error);
		}
	}
	if($debug) print_r($primary_keys);

	/*
			2. Check if the unique row exists
					example query:
							SELECT count(*) AS count FROM $table_name WHERE `key1`=? and `key2`=? ...
	*/

	$statement = "SELECT count(*) as count FROM `$table_name` WHERE ";
	$where_clause = "";
	$key_count = 0;
	foreach($primary_keys as $key=>$value) {
		if($where_clause != "") {
			$where_clause = $where_clause . " AND ";
		}
		$where_clause = $where_clause . "$key=?";
		$where_prepared_array[$key_count] = $value;
		$key_count++;
	}
	$statement = $statement . $where_clause;
	if($debug) print($statement . "\n");
	if($debug) print_r($where_prepared_array);
	$sth = $db->prepare($statement);
	$sth->execute($where_prepared_array);
	$db_row = $sth->fetch(PDO::FETCH_BOTH);
	$count = $db_row['count'];
	if($debug) print("Count = $count\n");

	// Build update and insert statements
	$insert_value_clause = "";
	$insert_column_clause = "";
	$update_value_clause = "";
	$key_count = 0;

	foreach($row as $key=>$value) {
		if($insert_value_clause != "") {
			$insert_value_clause = $insert_value_clause . ", ";
			$insert_column_clause = $insert_column_clause . ", ";
			$update_value_clause = $update_value_clause . ", ";
		}
		$insert_column_clause = $insert_column_clause . "`$key`";
		$insert_value_clause = $insert_value_clause . "?";
		$insert_prepared_array[$key_count] = $value;

		$update_value_clause = $update_value_clause . "`$key`=?";
		$update_prepared_array[$key_count] = $value;
		$key_count++;
	}

	$insert_statement = "INSERT INTO `$table_name` (" . $insert_column_clause . ") VALUES(" . $insert_value_clause . ")";
	$update_statement = "UPDATE `$table_name` SET " . $update_value_clause . " WHERE " . $where_clause;

	/*
		3. If the result of the above function is equal to zero use the data to build an insert statement
				example query:
						INSERT INTO $table_name VALUES (?,?,?,...);
	*/
	if( $count == 0 ) {
		$statement = $insert_statement;
		$prepared_array = $insert_prepared_array;
	}
	/*
		4. If the result of the above function is greater than zero use the data to build an update statement
			example query:
					UPDATE $table_name
					SET `nonkey3`=?,`nonkey4`=?,...
					WHERE `key1`=? and `key2`=? ...;
	*/
	else {
		$statement = $update_statement;
		$prepared_array = array_merge($update_prepared_array, $where_prepared_array);
	}
	if($debug) print($statement . "\n");
	if($debug) print_r($prepared_array);
	$sth = $db->prepare($statement);
	if( $sth->execute($prepared_array) == false ) {
		$arr = $sth->errorInfo();
		throw new Exception($arr[2]);
	}
}

function remove_backslashes($val)
{
  //print("<br /><pre>remove_backslashes($val)</pre><br />\n");
  if(is_array($val))
  {
    foreach($val as $k => $v)
      $val[$k] = remove_backslashes($v);
  } else if (!is_null($val))
    $val = stripslashes($val);
  return ($val);
}

function script_param($name)
{
  //print("<br /><pre>script_param(\$name=$name)</pre><br />\n");
  $val = NULL;
  if(isset($_GET[$name]))
    $val = $_GET[$name];
  else if(isset($_POST[$name]))
    $val = $_POST[$name];
  if(get_magic_quotes_gpc())
    $val = remove_backslashes($val);
  return($val);
}

// DuBois, Paul (2013-03-28). MySQL (5th Edition) (Developer's Library) (Kindle Locations 16498-16499). Pearson Education. Kindle Edition. 
function script_name () 
{ 
	return ($_SERVER["SCRIPT_NAME"]);
}
// WARNING: Make sure there are no spurious characters after the end of the PHP code
?>
