<?php

require_once($_SERVER['DOCUMENT_ROOT'] . '/sys/db.php');

foreach ($_POST as $paramName => $paramValue) {
  if ($paramName == "selectid")
    $mp_id = $paramValue;
  else if ($paramName == "Export")
    $export = $paramValue;
  else if ($paramName == "fields")
    $fields = explode(",", $paramValue);
  else if ($paramName == "values")
    $values = explode(",", $paramValue);
}

$comma = "";

$dal = new DAL();
$sql = "SELECT routinename " .
       "FROM misprocedure WHERE id = $mp_id LIMIT 1 " ;
$routinename = $dal->query($sql)->routinename;

//$sql = "";
for ($i=0; $i < count($fields); $i++) {
  $params .= "$comma'$values[$i]'";
  $comma = ",";
}

$sql = "CALL " . $routinename . "(" . $params . ");"; 
$result = $dal->query($sql);

if ($export == "true") {
  foreach ($result as $row) {
    $firstOf = true;
    foreach ($row as $value) {
      if ($firstOf) {
        $expFile .= $value;
        $firstOf = false;
      }
      else
        $expFile .= ",$value"; 
    }
    $expFile .= "\n";    
  }
  $result = $expFile;  
}

echo json_encode($result);

?>

