<?php
/*
 *    Execute a query on the BSC table of the mpe2018db DB (if not given as par.).

  Parameters:
    wquery: string with the WHERE clause

  Optional parameters:
    dbname: the name of the database to use (def. mpe2018db)
    user: the name of the user that connects to the server (def. mpeusr)
    password: the password for the given user (def. mpe2018pass)
    host: the nome or IP of the DB server (def. localhost)

  Last change: 07/06/2018
*/

// Verifichiamo i parametri di ingresso: tutti opzionali

if (empty($_GET['wquery']))
  $wquery =  '';
else
  $wquery =  ' WHERE '. $_GET['wquery'];


if (empty($_GET['nomedb']))
  $nomedb = 'mpe2018db';
else
  $nomedb = $_GET['nomedb'];

if (empty($_GET['utente']))
  $utente = 'mpeusr';
else
  $utente = $_GET['utente'];

if (empty($_GET['password']))
  $password = 'mpe2018pass';
else
  $password = $_GET['password'];

if (empty($_GET['host']))
  $host = 'localhost';
else
  $host = $_GET['host'];

if (empty($_GET['table']))
  $tab = 'sdss_sample';
else
  $tab = $_GET['table'];

// The list of fields to be returned by the  query - could be selectable by the user on the web interface!
  $flds = 'objid, rad, decd, r,  g-r as gmr, redshift';
  //$flds = '*';

// Build the query. Note the we do not imit the number of returned rows!
  $qry = "SELECT $flds FROM $tab $wquery";

//echo "$qry <br/>\n";

// Let's define an "object" ot type "array" to be returned to the calling program
  $data = array();

// Initialize some useful elements
  $data['status'] = 0;
  $data['errmsg'] = '';
  $data['nrows'] = 0;

// Wite the query
  $data['qry'] = $qry;


// Open the connection to the DB server
  $link = new mysqli( $host, $utente, $password, $nomedb );

// Verify that it is OK, otherwise stop here
  if ( $link->connect_errno ) {
    $data['status'] = -1;
    $data['errmsg'] = 'Error: Error: could not connect to the MySQL server: ('. $link->connect_errno .') '. $link->connect_error;
    echo json_encode( $data );
    return;
  }

// Execute the query
  $result = $link->query( $qry );

// Verify that the query gave a result, otherwise close the connection to the DB and exit
  if ( ! $result ) {
    $data['status'] = -2;
    $data['errmsg'] = 'Error: invalid query: '. $link->error;

// If OK the write, for each star, the information into the array of data identified by "objs"
  } else {
    $data['nrows'] = mysqli_num_rows($result);
    while ( $row = $result->fetch_assoc() )
      $data['objs'][] = $row;
  }

// Close the connection to the server
  if ($result) $result->free();
  mysqli_close($link);

// Encode the object data in JSON format and print it (it will be read by the calling program!)
  echo json_encode( $data );

?>
