<?php
/****************************************************************************************
 * DB IO - execute a database request and return the result  
 * This set uses ext/mysqli object oriented
 ****************************************************************************************
 * dbIO()   - execute a database request and return the results  
 *      arg1   - $host  - Name of the server (example 'localhost', or 'workshop.sps.nyu.edu')
 *      arg2   - $user  - Userid for the database 
 *      arg3   - $pswd  - Password for the database
 *      arg4   - $db    - Name of the database schema  
 *      arg5   - $sql   - SQL statement (select, insert, update, delete, etc.) 
 *      return - $data  - if sql is  SELECT and query OK then 2 dim. keyed array
 *                      - if sql not SELECT and DML   OK then number of rows affected
 *                      - if execution is not OK         then mysql error message 
****************************************************************************************/
function dbIO($host, $user, $pswd, $db, $sql)
{

    $connect  = new mysqli($host,$user,$pswd,$db);      //connect to host
    if (! $connect)
    {
        $error = $connect->connect_error;
        return($error);
    }

    $result = $connect->query($sql);                    //execute the query
    if (! $result)
    {
        $error = $connect->error;
        return($error);
    }

    $i=0;

    if (is_object($result))                             //If $result is an object
    {                                                   //SQL must have been a SELECT   
        while ($row = $result->fetch_assoc())           //loop through the query results
        {
            $data[$i++] = $row;                         //populate column values 
        }
        $result->free_result();                         //close the cursor/buffer
    }
    else                                                //SQL must not have been a SELECT
    {
        $data = $connect->affected_rows;                //return number of rows affected
    }    

    $connect->close();                                  //close the connection

    return($data);                                      //return the result of the execution
}
?>