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

$t1_name		 	= trim($_POST['t1_name']);
$id_from			= (int) trim($_POST['id_from']);
$id_to				= (int) trim($_POST['id_to']);

//range clause
$rangeclause = "";
if($id_from>0){
	if($id_to>0){
		$rangeclause = "where id>='{$id_from}' and id<='{$id_to}' ";
	}else{
		$rangeclause = "where id>='{$id_from}' ";
	}
}

if(($lenomatches_1==$lenomatches_2) && ($lenomatches_1==$lenomatches_2)){
	echo "<br />'FIND AND REPLACE' STARTED<br />";
	$res = $DB->execute("select id,".toCSL($matches_1).",".toCSL($replaces_1)." from `{$t1_name}` {$rangeclause}order by id ASC");
	if(!is_null($res)){
		$res = $res[0];
		while($W = $DB->nextRow($res)){
			$id = $W['id'];
			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 #{$id}";
			}else{
				echo "<br />Error at #{$id}";
			}
		}
		echo "<br />ENDED<br />";
	}
}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;
}
?>