<?php require_once("../../classes/DBConnection.php"); $DB = new DBConnection();

$t1_name		 	= trim($_POST['t1_name']);
$t1_match_cols		= explode(',',trim($_POST['t1_match_cols']));
$t1_replace_cols	= explode(',',trim($_POST['t1_replace_cols']));

$t2_name			= trim($_POST['t2_name']);
$t2_match_cols		= explode(',',trim($_POST['t2_match_cols']));
$t2_replace_cols	= explode(',',trim($_POST['t2_replace_cols']));

//Clean up strings
$matches_1 = array();
$matches_1_val = array();
foreach($t1_match_cols as $m){
	$m = trim($m); if($m=="") continue;
	$matches_1[] = $m;
}

$matches_2 = array();
$matches_2_val = array();
foreach($t2_match_cols as $m){
	$m = trim($m); if($m=="") continue;
	$matches_2[] = $m;
}

$replaces_1 = array();
$replaces_1_val = array();
foreach($t1_replace_cols as $r){
	$r = trim($r); if($r=="") continue;
	$replaces_1[] = $r;
}

$replaces_2 = array();
$replaces_2_val = array();
foreach($t2_replace_cols as $r){
	$r = trim($r); if($r=="") continue;
	$replaces_2[] = $r;
}

$lenomatches_1 = sizeof($matches_1);
$lenomatches_2 = sizeof($matches_2);

$lenoreplaces_1 = sizeof($replaces_1);
$lenoreplaces_2 = sizeof($replaces_2);

if(($lenomatches_1==$lenomatches_2) && ($lenomatches_1==$lenomatches_2)){
	$no = 0;
	echo "<br />'FIND AND REPLACE' STARTED (VERSION 2)<hr />";
	$res = $DB->execute("select ".toCSL($matches_1).",".toCSL($replaces_1)." from `{$t1_name}` order by id ASC");
	if(!is_null($res)){
		$res = $res[0];
		while($W = $DB->nextRow($res)){
			$no++;
			for($i=0; $i<sizeof($replaces_1); $i++){
				$replaces_1_val[$i] = trim($W[$replaces_1[$i]]);
			}
			for($i=0; $i<sizeof($matches_1); $i++){
				$matches_1_val[$i] = trim($W[$matches_1[$i]]);
			}
			if($DB->simpleQuery("update `{$t2_name}` set ".holePegStr($replaces_2, $replaces_1_val)." where ".andCondition($matches_2, $matches_1_val))){
				echo "<br />Done at #{$no}";
			}else{
				echo "<br />Error at #{$no}";
			}
		}
		echo "<br />ENDED<hr />";
	}
}else{
	echo "<br />SIZE MISMATCH ERROR!<br />Please check<br />";
}

function holePegStr($holes, $pegs){
	global $DB;
	$hpstr = "";
	for($i=0; $i<sizeof($holes); $i++){
		$hpstr .= ",`{$holes[$i]}`='".$DB->escape_string($pegs[$i])."'";
	}
	$hpstr = substr($hpstr,1);
	return $hpstr;
}

function andCondition($names, $values){
	global $DB;
	$cond = "";
	for($i=0; $i<sizeof($names); $i++){
		$cond .= " and `{$names[$i]}`='".$DB->escape_string($values[$i])."'";
	}
	$cond = substr($cond, 5);
	return $cond;
}

function toCSL($arr){
	global $DB;
	$ret = "";
	foreach($arr as $a){ $ret .= ",`".$DB->escape_string($a)."`"; }
	$ret = substr($ret,1);
	return $ret;
}
?>