function uploadImageData($db, $file, $currentPictureId, $table, $id)
 {
     // insert the new record into the media's table and load the
     // corresponding blob with the media's data
     // (we use oracle's pseudo column rowid which identifies a row
     // within a table (but not within a database) to refer to the
     // right record later on)
     $sql = "DECLARE\n                        obj ORDSYS.ORDImage;\n                        iblob BLOB;\n                BEGIN\n                        SELECT image INTO obj FROM {$table}\n                        WHERE {$id} = {$currentPictureId} FOR UPDATE;\n\n                        iblob := obj.source.localData;\n                        :extblob := iblob;\n\n                        UPDATE {$table} SET image = obj WHERE {$id} = {$currentPictureId};\n                END;";
     // the function OCINewDescriptor allocates storage to hold descriptors or
     // lob locators.
     // see http://www.php.net/manual/en/function.ocinewdescriptor.php
     $blob = OCINewDescriptor($db, OCI_D_LOB);
     $sql = strtr($sql, chr(13) . chr(10), " ");
     $stmt = OCIParse($db, $sql);
     // the function OCIBindByName binds a PHP variable to a oracle placeholder
     // (whether the variable will be used for input or output will be determined
     // run-time, and the necessary storage space will be allocated)
     // see http://www.php.net/manual/en/function.ocibindbyname.php
     OCIBindByName($stmt, ':extblob', $blob, -1, OCI_B_BLOB);
     echo "{$this->log} - {$sql} <br />";
     OCIExecute($stmt, OCI_DEFAULT);
     // read the files data and load it into the blob
     $blob->savefile($file);
     OCIFreeStatement($stmt);
     $blob->free();
 }
Esempio n. 2
0
function executeBoundSQL($cmdstr, $list)
{
    /* Sometimes a same statement will be excuted for severl times, only
    	 the value of variables need to be changed.
    	 In this case you don't need to create the statement several times; 
    	 using bind variables can make the statement be shared and just 
    	 parsed once. This is also very useful in protecting against SQL injection. See example code below for       how this functions is used */
    global $db_conn, $success;
    $statement = OCIParse($db_conn, $cmdstr);
    if (!$statement) {
        echo "<br>Cannot parse the following command: " . $cmdstr . "<br>";
        $e = OCI_Error($db_conn);
        echo htmlentities($e['message']);
        $success = False;
    }
    foreach ($list as $tuple) {
        foreach ($tuple as $bind => $val) {
            //echo $val;
            //echo "<br>".$bind."<br>";
            OCIBindByName($statement, $bind, $val);
            unset($val);
            //make sure you do not remove this. Otherwise $val will remain in an array object wrapper which will not be recognized by Oracle as a proper datatype
        }
        $r = OCIExecute($statement, OCI_DEFAULT);
        if (!$r) {
            echo "<br>Cannot execute the following command: " . $cmdstr . "<br>";
            $e = OCI_Error($statement);
            // For OCIExecute errors pass the statementhandle
            echo htmlentities($e['message']);
            echo "<br>";
            $success = False;
        }
    }
}
Esempio n. 3
0
function add_image($name, $imagetype, $file)
{
    if (!is_null($file)) {
        if ($file["error"] != 0 || $file["size"] == 0) {
            error("Incorrect Image");
        } else {
            if ($file["size"] < 1024 * 1024) {
                global $DB;
                $imageid = get_dbid("images", "imageid");
                $image = fread(fopen($file["tmp_name"], "r"), filesize($file["tmp_name"]));
                if ($DB['TYPE'] == "ORACLE") {
                    DBstart();
                    $lobimage = OCINewDescriptor($DB['DB'], OCI_D_LOB);
                    $stid = OCIParse($DB['DB'], "insert into images (imageid,name,imagetype,image)" . " values ({$imageid}," . zbx_dbstr($name) . "," . $imagetype . ",EMPTY_BLOB())" . " return image into :image");
                    if (!$stid) {
                        $e = ocierror($stid);
                        error("Parse SQL error [" . $e["message"] . "] in [" . $e["sqltext"] . "]");
                        return false;
                    }
                    OCIBindByName($stid, ':image', $lobimage, -1, OCI_B_BLOB);
                    if (!OCIExecute($stid, OCI_DEFAULT)) {
                        $e = ocierror($stid);
                        error("Execute SQL error [" . $e["message"] . "] in [" . $e["sqltext"] . "]");
                        return false;
                    }
                    $result = DBend($lobimage->save($image));
                    if (!$result) {
                        error("Couldn't save image!\n");
                        return false;
                    }
                    $lobimage->free();
                    OCIFreeStatement($stid);
                    return $stid;
                } else {
                    if ($DB['TYPE'] == "POSTGRESQL") {
                        $image = pg_escape_bytea($image);
                    } else {
                        if ($DB['TYPE'] == "SQLITE3") {
                            $image = bin2hex($image);
                        }
                    }
                }
                return DBexecute("insert into images (imageid,name,imagetype,image)" . " values ({$imageid}," . zbx_dbstr($name) . "," . $imagetype . "," . zbx_dbstr($image) . ")");
            } else {
                error("Image size must be less than 1Mb");
            }
        }
    } else {
        error("Select image to download");
    }
    return false;
}
Esempio n. 4
0
function QueryB($sql)
{
    global $conn;
    $stmt = OCIParse($conn, $sql);
    $DBody = OCINewDescriptor($conn, OCI_D_LOB);
    OCIBindByName($stmt, ":Body_Loc", $DBody, -1, OCI_B_BLOB);
    $err = OCIExecute($stmt, OCI_DEFAULT);
    if (!$err) {
        $error = OCIError($stmt);
        //echo '<strong>Произошла ошибка: <font color="#889999">'.$error["message"].'</font><br>Запрос: <font color="#889999">'.$error["sqltext"].'</font></strong>';
        QError($error);
        die;
    }
    return $DBody;
}
 function retrieveImage($db, $id, $table, $column)
 {
     // the function OCINewDescriptor allocates storage to hold descriptors or
     // lob locators,
     // see http://www.php.net/manual/en/function.ocinewdescriptor.php
     $data;
     $blob = OCINewDescriptor($db, OCI_D_LOB);
     // construct the sql query with which we will get the media's data
     $sql = "DECLARE\n                        obj ORDSYS.ORDImage;\n                BEGIN\n                        SELECT {$column} INTO obj FROM {$table} WHERE picture_id = :id;\n                        :extblob := obj.getContent;\n                END;";
     $sql = strtr($sql, chr(13) . chr(10), " ");
     $stmt = OCIParse($db, $sql);
     // the function OCIBindByName binds a PHP variable to a oracle placeholder
     // (wheter the variable will be used for input or output will be determined
     // run-time, and the necessary storage space will be allocated)
     // see http://www.php.net/manual/en/function.ocibindbyname.php
     OCIBindByName($stmt, ':extBlob', $blob, -1, OCI_B_BLOB);
     OCIBindByName($stmt, ':id', $id);
     OCIExecute($stmt, OCI_DEFAULT);
     // load the binary data
     $data = $blob->load();
     return $data;
 }
Esempio n. 6
0
 /**
  * Execute a prepared query statement helper method.
  *
  * @param mixed $result_class string which specifies which result class to use
  * @param mixed $result_wrap_class string which specifies which class to wrap results in
  * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
  * @access private
  */
 function &_execute($result_class = true, $result_wrap_class = false)
 {
     if (is_null($this->statement)) {
         $result =& parent::_execute($result_class, $result_wrap_class);
         return $result;
     }
     $this->db->last_query = $this->query;
     $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
     if ($this->db->getOption('disable_query')) {
         $result = $this->is_manip ? 0 : null;
         return $result;
     }
     $connection = $this->db->getConnection();
     if (PEAR::isError($connection)) {
         return $connection;
     }
     $result = MDB2_OK;
     $lobs = $quoted_values = array();
     $i = 0;
     foreach ($this->positions as $parameter) {
         if (!array_key_exists($parameter, $this->values)) {
             return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, 'Unable to bind to missing placeholder: ' . $parameter, __FUNCTION__);
         }
         $value = $this->values[$parameter];
         $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
         if ($type == 'clob' || $type == 'blob') {
             $lobs[$i]['file'] = false;
             if (is_resource($value)) {
                 $fp = $value;
                 $value = '';
                 while (!feof($fp)) {
                     $value .= fread($fp, 8192);
                 }
             } elseif (preg_match('/^(\\w+:\\/\\/)(.*)$/', $value, $match)) {
                 $lobs[$i]['file'] = true;
                 if ($match[1] == 'file://') {
                     $value = $match[2];
                 }
             }
             $lobs[$i]['value'] = $value;
             $lobs[$i]['descriptor'] = @OCINewDescriptor($connection, OCI_D_LOB);
             if (!is_object($lobs[$i]['descriptor'])) {
                 $result = $this->db->raiseError(null, null, null, 'Unable to create descriptor for LOB in parameter: ' . $parameter, __FUNCTION__);
                 break;
             }
             $lob_type = $type == 'blob' ? OCI_B_BLOB : OCI_B_CLOB;
             if (!@OCIBindByName($this->statement, ':' . $parameter, $lobs[$i]['descriptor'], -1, $lob_type)) {
                 $result = $this->db->raiseError($this->statement, null, null, 'could not bind LOB parameter', __FUNCTION__);
                 break;
             }
         } else {
             $quoted_values[$i] = $this->db->quote($value, $type, false);
             if (PEAR::isError($quoted_values[$i])) {
                 return $quoted_values[$i];
             }
             if (!@OCIBindByName($this->statement, ':' . $parameter, $quoted_values[$i])) {
                 $result = $this->db->raiseError($this->statement, null, null, 'could not bind non LOB parameter', __FUNCTION__);
                 break;
             }
         }
         ++$i;
     }
     $lob_keys = array_keys($lobs);
     if (!PEAR::isError($result)) {
         $mode = !empty($lobs) || $this->db->in_transaction ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
         if (!@OCIExecute($this->statement, $mode)) {
             $err =& $this->db->raiseError($this->statement, null, null, 'could not execute statement', __FUNCTION__);
             return $err;
         }
         if (!empty($lobs)) {
             foreach ($lob_keys as $i) {
                 if (!is_null($lobs[$i]['value']) && $lobs[$i]['value'] !== '') {
                     if ($lobs[$i]['file']) {
                         $result = $lobs[$i]['descriptor']->savefile($lobs[$i]['value']);
                     } else {
                         $result = $lobs[$i]['descriptor']->save($lobs[$i]['value']);
                     }
                     if (!$result) {
                         $result = $this->db->raiseError(null, null, null, 'Unable to save descriptor contents', __FUNCTION__);
                         break;
                     }
                 }
             }
             if (!PEAR::isError($result)) {
                 if (!$this->db->in_transaction) {
                     if (!@OCICommit($connection)) {
                         $result = $this->db->raiseError(null, null, null, 'Unable to commit transaction', __FUNCTION__);
                     }
                 } else {
                     ++$this->db->uncommitedqueries;
                 }
             }
         }
     }
     $lob_keys = array_keys($lobs);
     foreach ($lob_keys as $i) {
         $lobs[$i]['descriptor']->free();
     }
     if (PEAR::isError($result)) {
         return $result;
     }
     if ($this->is_manip) {
         $affected_rows = $this->db->_affectedRows($connection, $this->statement);
         return $affected_rows;
     }
     $result =& $this->db->_wrapResult($this->statement, $this->result_types, $result_class, $result_wrap_class, $this->limit, $this->offset);
     $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
     return $result;
 }
Esempio n. 7
0
$amount = $_POST["amount"];
$refrence = $_POST["refrence"];
$transtype = 'PURCHASE';
$desc = $_POST["desc"];
$bid = $_SESSION['Branchcode'];
if ($amount <= 499) {
    echo "<SCRIPT LANGUAGE='JavaScript'>\r        alert('Sorry, you can only make a purchase above KSh[500], thank you!')\r        window.location.href='../indpurchase.php?id={$member}&acid={$account}'\t\r        </SCRIPT>";
} else {
    if ($reference == '') {
        echo "<SCRIPT LANGUAGE='JavaScript'>\r        window.alert('Please enter a valid Reference code, thank you!')\r        window.location.href='../indpurchase.php?id={$member}&acid={$account}'\t\r        </SCRIPT>";
    } else {
        $mysql = "select AMOUNT, PORTFOLIO, BANKACCDETS, DOC_NO FROM TRANS_AMOUNT WHERE DOC_NO='" . $refrence . "'";
        $resbank = oci_parse($conn, $mysql) or die(" ");
        oci_execute($resbank);
        $numrows = oci_fetch_all($resbank, $res);
        if ($numrows <= 0) {
            $sql = "INSERT INTO trans_amount(trans_type,member_no, full_name,account_no, amount,portfolio,mop, u_name, doc_no, bnkcode, BANKACCDETS ) VALUES('" . $transtype . "','" . $member . "','" . $name . "','" . $account . "','" . $amount . "','" . $desc . "','Funds Transfer','" . $_SESSION['username'] . "','" . $refrence . "','" . $_SESSION['Branchcode'] . "','" . $_SESSION['Branchname'] . "')  returning TRANS_ID into :id ";
            $result = OCIParse($conn, $sql);
            OCIBindByName($result, ":ID", $id, 32);
            OCI_Execute($result);
            if (!oci_parse($conn, $sql)) {
                echo "<SCRIPT LANGUAGE='JavaScript'>\r\t\t\t\r\t\t\t\r\r\$('#content').notifyModal({\r\r\t\t\t\r\rduration : 2500,\r\r\t\t\t\r\rplacement : 'center',\r\r\t\t\t\r\roverlay : true,\r\r\t\t\t\r\rtype : 'notify',\r\r\t\t\t\r\ronClose : function(){ }\r});\r\r\t\t'\r\t\t\t</SCRIPT>";
            } else {
                oci_close($conn);
                echo "<SCRIPT LANGUAGE='JavaScript'>\r\t\t\twindow.alert('Purchase Posted successfully, Transaction ID [{$id}].')\r\t\t\twindow.location.href='../indsearch.php'\r\t\t\t</SCRIPT>";
            }
        } else {
            echo "<SCRIPT LANGUAGE='JavaScript'>\r        window.alert('Sorry the Refference Number already been used. Please Enter the correct Refference ID from Finacle!')\r\t\twindow.location.href='../indpurchase.php?id={$member}&acid={$account}'\t\t\r        </SCRIPT>";
        }
    }
}
Esempio n. 8
0
function sqlCompile($Query_String)
{
    $db = new clsDBdatabase();
    $db->Provider->sqoe = 0;
    $esto = array(chr(10), chr(9), chr(13));
    $porEsto = array("\n", "\t", " ");
    $parse = '
	declare
		c integer := dbms_sql.open_cursor();
	begin
		dbms_sql.parse(c, :STMT, dbms_sql.native);
		dbms_sql.close_cursor(c);
	end;
	';
    $plsql = trim(str_replace($esto, $porEsto, $Query_String));
    #echo $plsql ;
    #$Query_String = 'select a from dual';
    $db->bind('STMT', $plsql, 4000, SQLT_CHR);
    #$db->query('BEGIN '.trim(str_replace($esto, $porEsto, $parse)).' END;');
    $db->Query_ID = OCIParse($db->Link_ID, 'BEGIN ' . trim(str_replace($esto, $porEsto, $parse)) . ' END;');
    if (!$db->Query_ID) {
        $db->Error = OCIError($db->Link_ID);
        echo 'ERROR ' . OCIError($db->Link_ID);
    }
    if (sizeof($db->Provider->Binds) > 0) {
        foreach ($db->Provider->Binds as $parameter_name => $parameter_values) {
            if ($parameter_values[2] == OCI_B_CURSOR) {
                $this->db[$parameter_name][0] = OCINewCursor($db->Link_ID);
            }
            if ($parameter_values[2] == 0) {
                OCIBindByName($db->Query_ID, ":" . $parameter_name, $db->Provider->Binds[$parameter_name][0], $parameter_values[1]);
            } else {
                OCIBindByName($db->Query_ID, ":" . $parameter_name, $db->Provider->Binds[$parameter_name][0], $parameter_values[1], $parameter_values[2]);
            }
        }
    }
    @OCIExecute($db->Query_ID);
    $db->Error = OCIError($db->Query_ID);
    #var_dump($db->Error);
    $SQLCODE = $db->Error['code'];
    $SQLERRMSG = explode('ORA-06512', $db->Error['message']);
    $SQLERRMSG = $SQLERRMSG[0];
    $error = new stdClass();
    $error->SQLCODE = !$SQLCODE ? 0 : $SQLCODE;
    $error->SQLERRMSG = $SQLERRMSG;
    return $error;
}
 /**
  * Lance une procédure stockées sur la connextion courante
  * @param string $pProcedure la procédure a lancer
  * @param array $pParams un tableau de paramètre à donner à la procédure
  *  le tableau est de la forme $pParams['nom'] = array ('type'=>, 'length'), 'in'=>, ''
  * @return array un tableau de résultat avec array['results'] = résultats,
  *    array['params']['nomParam'] = valeur
  */
 public function doProcedure($pProcedure, $pParams)
 {
     CopixLog::log($pProcedure . var_export($pParams, true), 'query', CopixLog::INFORMATION);
     //Préparation de la requête
     $stmt = @ociparse($this->_ct, $pProcedure);
     if ($stmt === false) {
         throw new CopixDBException('[CopixDB] Impossible de préparer la procédure ' . $pProcedure);
     }
     //On analyse les paramètres
     $arVariablesName = array();
     $arVariables = array();
     foreach ($pParams as $name => $param) {
         $variableName = substr($name, 1);
         if (!is_array($param)) {
             ${$variableName} = $param;
             if (!OCIBindByName($stmt, $name, ${$variableName}, 255)) {
                 throw new Exception("[CopixDB] Impossible de rapprocher '{$name}' avec '" . ${$variableName} . "' taille " . $arVariables[$variableName]['maxlength'] . " type " . $this->_convertQueryParam($arVariables[$variableName]['type']));
             }
             $arVariables[$variableName]['type'] = 'AUTO';
             $arVariables[$variableName]['value'] = $param;
         } else {
             if (!isset(${$variableName})) {
                 ${$variableName} = isset($param['value']) ? $param['value'] : null;
             }
             $arVariables[$variableName] = $param;
             if (!isset($arVariables[$variableName]['type'])) {
                 $arVariables[$variableName]['type'] = CopixDBQueryParam::DB_AUTO;
             }
             if (!isset($arVariables[$variableName]['maxlength'])) {
                 $arVariables[$variableName]['maxlength'] = -1;
             }
             if ($arVariables[$variableName]['type'] === CopixDBQueryParam::DB_CURSOR) {
                 ${$variableName} = oci_new_cursor($this->_ct);
             }
             if (!OCIBindByName($stmt, $name, ${$variableName}, $arVariables[$variableName]['maxlength'], $this->_convertQueryParam($arVariables[$variableName]['type']))) {
                 oci_free_statement($stmt);
                 throw new CopixDBException("[CopixDB] Impossible de rapprocher '{$name}' avec '" . ${$variableName} . "' taille " . $arVariables[$variableName]['maxlength'] . " type " . $this->_convertQueryParam($arVariables[$variableName]['type']));
             }
         }
     }
     //on exécute la requête
     if (!ociexecute($stmt, OCI_DEFAULT)) {
         $statementErrors = oci_error($stmt);
         oci_free_statement($stmt);
         throw new CopixDBException('[CopixDB] Impossible d\'exécuter la procédure ' . $pProcedure . ' - ' . var_dump($statementErrors) . ' avec les variables ' . var_dump($arVariables));
     }
     //analyse des résultats
     foreach ($arVariables as $name => $value) {
         //Si c'est un curseur
         if ($value['type'] === CopixDBQueryParam::DB_CURSOR) {
             if (!@ociexecute(${$name})) {
                 oci_free_statement(${$name});
                 oci_free_statement($stmt);
                 throw new CopixDBException("Impossible de récupérer l'ensemble de résultat de la variable {$name}");
             }
             $toReturn[':' . $name] = array();
             while ($r = oci_fetch_object(${$name})) {
                 $toReturn[':' . $name][] = $r;
             }
             oci_free_statement(${$name});
         } else {
             $toReturn[':' . $name] = ${$name};
         }
     }
     //On commit si le mode est autocommit
     if ($this->_autoCommitMode == self::OCI_AUTO_COMMIT) {
         $this->commit();
     }
     oci_free_statement($stmt);
     CopixLog::log('Terminé', 'Procedure');
     return $toReturn;
 }
Esempio n. 10
0
 /**
  * Executes a DB statement prepared with prepare().
  *
  * To determine how many rows of a result set get buffered using
  * ocisetprefetch(), see the "result_buffering" option in setOptions().
  * This option was added in Release 1.7.0.
  *
  * @param resource  $stmt  a DB statement resource returned from prepare()
  * @param mixed  $data  array, string or numeric data to be used in
  *                      execution of the statement.  Quantity of items
  *                      passed must match quantity of placeholders in
  *                      query:  meaning 1 for non-array items or the
  *                      quantity of elements in the array.
  *
  * @return mixed  returns an oic8 result resource for successful SELECT
  *                queries, DB_OK for other successful queries.
  *                A DB error object is returned on failure.
  *
  * @see DB_oci8::prepare()
  */
 function &execute($stmt, $data = array())
 {
     $data = (array) $data;
     $this->last_parameters = $data;
     $this->last_query = $this->_prepared_queries[(int) $stmt];
     $this->_data = $data;
     $types = $this->prepare_types[(int) $stmt];
     if (count($types) != count($data)) {
         $tmp = $this->raiseError(DB_ERROR_MISMATCH);
         return $tmp;
     }
     $i = 0;
     foreach ($data as $key => $value) {
         if ($types[$i] == DB_PARAM_MISC) {
             /*
              * Oracle doesn't seem to have the ability to pass a
              * parameter along unchanged, so strip off quotes from start
              * and end, plus turn two single quotes to one single quote,
              * in order to avoid the quotes getting escaped by
              * Oracle and ending up in the database.
              */
             $data[$key] = preg_replace("/^'(.*)'\$/", "\\1", $data[$key]);
             $data[$key] = str_replace("''", "'", $data[$key]);
         } elseif ($types[$i] == DB_PARAM_OPAQUE) {
             $fp = @fopen($data[$key], 'rb');
             if (!$fp) {
                 $tmp = $this->raiseError(DB_ERROR_ACCESS_VIOLATION);
                 return $tmp;
             }
             $data[$key] = fread($fp, filesize($data[$key]));
             fclose($fp);
         } elseif ($types[$i] == DB_PARAM_SCALAR) {
             // Floats have to be converted to a locale-neutral
             // representation.
             if (is_float($data[$key])) {
                 $data[$key] = $this->quoteFloat($data[$key]);
             }
         }
         if (!@OCIBindByName($stmt, ':bind' . $i, $data[$key], -1)) {
             $tmp = $this->oci8RaiseError($stmt);
             return $tmp;
         }
         $this->last_query = str_replace(':bind' . $i, $this->quoteSmart($data[$key]), $this->last_query);
         $i++;
     }
     if ($this->autocommit) {
         $success = @OCIExecute($stmt, OCI_COMMIT_ON_SUCCESS);
     } else {
         $success = @OCIExecute($stmt, OCI_DEFAULT);
     }
     if (!$success) {
         $tmp = $this->oci8RaiseError($stmt);
         return $tmp;
     }
     $this->last_stmt = $stmt;
     if ($this->manip_query[(int) $stmt] || $this->_next_query_manip) {
         $this->_last_query_manip = true;
         $this->_next_query_manip = false;
         $tmp = DB_OK;
     } else {
         $this->_last_query_manip = false;
         @ocisetprefetch($stmt, $this->options['result_buffering']);
         $tmp = new DB_result($this, $stmt);
     }
     return $tmp;
 }
Esempio n. 11
0
/**
 * Created by PhpStorm.
 * User: Allan Wiz
 * Date: 3/25/15
 * Time: 10:16 AM
 */
session_start();
//global $session, $database;
require '../classes/aardb_conn.php';
require '../functions/sanitize.php';
foreach ($_POST as $key => $value) {
    ${$key} = $value;
    //echo $key = $value;
}
//$dobdate=ConvertSDate($dob);
####
//$dob = substr($dob, 0, 10);
//$dob = date("d/m/Y", strtotime($dob));
$stmt = OCIParse($conn, "insert into member_no values (MEMBERNUMBER_SEQ.nextval) returning MEMBERNO into :id");
OCIBindByName($stmt, ":ID", $id, 32);
OCI_Execute($stmt);
if (strlen($id) == 1) {
    $memberno = "0000000{$id}";
} else {
    if (strlen($id) == 2) {
        $memberno = "000000{$id}";
    } else {
        if (strlen($id) == 3) {
            $memberno = "00000{$id}";
        } else {
Esempio n. 12
0
 function insertPictureIfNotExists($db, $picture)
 {
     $picture->id = $this->dbIdFetcher->fetchPictureId($db, $picture);
     if (is_null($picture->id)) {
         $sql = "INSERT INTO pictures (\n                    picture_id, name, description,\n                    image, image_sig,\n                    creation_date, upload_date,\n                    artist_fk, artist_safety_level,\n                    museum_ownes_fk, museum_exhibits_fk,\n                    museum_exhibits_startdate, museum_exhibits_enddate,\n                    owner_fk)\n                    VALUES (pictures_seq.nextval,\n                    '{$picture->name}',\n                    '{$picture->description}',\n                    ORDSYS.ORDImage.init(),\n                    ORDSYS.ORDImageSignature.init(),\n                    TO_DATE('{$picture->creation_date}', 'dd.mm.yyyy'),\n                    TO_DATE('{$picture->upload_date}', 'dd.mm.yyyy'),\n                    {$picture->artist_fk},\n                    {$picture->artist_safety_level},";
         /** Add Optional Parameters **/
         if (empty($picture->museum_owns_fk)) {
             $sql .= "NULL, ";
         } else {
             $sql .= "{$picture->museum_owns_fk} , ";
         }
         if (empty($picture->museum_exhibits_fk)) {
             $sql .= "NULL, NULL, NULL, ";
         } else {
             $sql .= "{$picture->museum_exhibits_fk} ,\n                    TO_DATE('{$picture->museum_exhibits_startdate}', 'dd.mm.yyyy'),\n                    TO_DATE('{$picture->museum_exhibits_enddate}', 'dd.mm.yyyy'), ";
         }
         if (empty($picture->owner_fk)) {
             $sql .= "NULL)";
         } else {
             $sql .= "{$picture->owner_fk})";
         }
         $sql .= "returning picture_id into :picture_id";
         echo "{$this->log} - {$sql} <br />";
         $stmt = oci_parse($db, $sql);
         $currentPictureId;
         OCIBindByName($stmt, ":picture_id", $currentPictureId, 32);
         oci_execute($stmt, OCI_NO_AUTO_COMMIT);
         /** Load image data **/
         $this->dbImageUploader = new DbImageUploader();
         $this->dbImageUploader->uploadImageData($db, $picture->image_path . $picture->image_name, $currentPictureId, 'pictures', 'picture_id');
         /** Create ImageSignature **/
         $sql = "DECLARE imageObj ORDSYS.ORDImage;\n                            image_sigObj ORDSYS.ORDImageSignature;\n                    BEGIN\n                        SELECT image, image_sig INTO imageObj, image_sigObj\n                        FROM pictures WHERE picture_id = {$currentPictureId} FOR UPDATE;\n                        image_sigObj.generateSignature(imageObj);\n                    UPDATE pictures SET image_sig = image_sigObj\n                    WHERE picture_id = {$currentPictureId};\n                    COMMIT; END;";
         echo "{$this->log} - {$sql} <br />";
         $stmt = oci_parse($db, $sql);
         oci_execute($stmt, OCI_NO_AUTO_COMMIT);
         oci_commit($db);
     }
 }
Esempio n. 13
0
 /**
  * Executes a DB statement prepared with prepare().
  *
  * @param resource  $stmt  a DB statement resource returned from prepare()
  * @param mixed  $data  array, string or numeric data to be used in
  *                      execution of the statement.  Quantity of items
  *                      passed must match quantity of placeholders in
  *                      query:  meaning 1 for non-array items or the
  *                      quantity of elements in the array.
  * @return int returns an oci8 result resource for successful
  * SELECT queries, DB_OK for other successful queries.  A DB error
  * code is returned on failure.
  * @see DB_oci::prepare()
  */
 function &execute($stmt, $data = array())
 {
     if (!is_array($data)) {
         $data = array($data);
     }
     $this->_data = $data;
     $types =& $this->prepare_types[$stmt];
     if (count($types) != count($data)) {
         $tmp =& $this->raiseError(DB_ERROR_MISMATCH);
         return $tmp;
     }
     $i = 0;
     foreach ($data as $key => $value) {
         if ($types[$i] == DB_PARAM_MISC) {
             /*
              * Oracle doesn't seem to have the ability to pass a
              * parameter along unchanged, so strip off quotes from start
              * and end, plus turn two single quotes to one single quote,
              * in order to avoid the quotes getting escaped by
              * Oracle and ending up in the database.
              */
             $data[$key] = preg_replace("/^'(.*)'\$/", "\\1", $data[$key]);
             $data[$key] = str_replace("''", "'", $data[$key]);
         } elseif ($types[$i] == DB_PARAM_OPAQUE) {
             $fp = @fopen($data[$key], 'rb');
             if (!$fp) {
                 $tmp =& $this->raiseError(DB_ERROR_ACCESS_VIOLATION);
                 return $tmp;
             }
             $data[$key] = fread($fp, filesize($data[$key]));
             fclose($fp);
         }
         if (!@OCIBindByName($stmt, ':bind' . $i, $data[$key], -1)) {
             $tmp = $this->oci8RaiseError($stmt);
             return $tmp;
         }
         $i++;
     }
     if ($this->autoCommit) {
         $success = @OCIExecute($stmt, OCI_COMMIT_ON_SUCCESS);
     } else {
         $success = @OCIExecute($stmt, OCI_DEFAULT);
     }
     if (!$success) {
         $tmp = $this->oci8RaiseError($stmt);
         return $tmp;
     }
     $this->last_stmt = $stmt;
     if ($this->manip_query[(int) $stmt]) {
         $tmp = DB_OK;
     } else {
         $tmp =& new DB_result($this, $stmt);
     }
     return $tmp;
 }
Esempio n. 14
0
 /**
  * Execute a query
  * @param string $query the SQL query
  * @return mixed result identifier if query executed, else MDB2_error
  * @access private
  **/
 function _doQuery($query, $ismanip = null, $prepared_query = 0)
 {
     $lobs = 0;
     $success = MDB2_OK;
     $result = 0;
     $descriptors = array();
     if ($prepared_query) {
         $columns = '';
         $variables = '';
         for (reset($this->clobs[$prepared_query]), $clob = 0; $clob < count($this->clobs[$prepared_query]); $clob++, next($this->clobs[$prepared_query])) {
             $clob_stream = key($this->clobs[$prepared_query]);
             $descriptors[$clob_stream] = @OCINewDescriptor($this->connection, OCI_D_LOB);
             if (!is_object($descriptors[$clob_stream])) {
                 $success = $this->raiseError(MDB2_ERROR, null, null, 'Could not create descriptor for clob parameter');
                 break;
             }
             $parameter = $GLOBALS['_MDB2_LOBs'][$clob_stream]->parameter;
             $columns .= ($lobs == 0 ? ' RETURNING ' : ',') . $this->prepared_queries[$prepared_query - 1]['fields'][$parameter - 1];
             $variables .= ($lobs == 0 ? ' INTO ' : ',') . ':clob' . $parameter;
             ++$lobs;
         }
         if (!MDB2::isError($success)) {
             for (reset($this->blobs[$prepared_query]), $blob = 0; $blob < count($this->blobs[$prepared_query]); $blob++, next($this->blobs[$prepared_query])) {
                 $blob_stream = key($this->blobs[$prepared_query]);
                 $descriptors[$blob_stream] = @OCINewDescriptor($this->connection, OCI_D_LOB);
                 if (!is_object($descriptors[$blob_stream])) {
                     $success = $this->raiseError(MDB2_ERROR, null, null, 'Could not create descriptor for blob parameter');
                     break;
                 }
                 $parameter = $GLOBALS['_MDB2_LOBs'][$blob_stream]->parameter;
                 $columns .= ($lobs == 0 ? ' RETURNING ' : ',') . $this->prepared_queries[$prepared_query - 1]['fields'][$parameter - 1];
                 $variables .= ($lobs == 0 ? ' INTO ' : ',') . ':blob' . $parameter;
                 ++$lobs;
             }
             $query .= $columns . $variables;
         }
     }
     if (!MDB2::isError($success)) {
         if ($statement = @OCIParse($this->connection, $query)) {
             if ($lobs) {
                 for (reset($this->clobs[$prepared_query]), $clob = 0; $clob < count($this->clobs[$prepared_query]); $clob++, next($this->clobs[$prepared_query])) {
                     $clob_stream = key($this->clobs[$prepared_query]);
                     $parameter = $GLOBALS['_MDB2_LOBs'][$clob_stream]->parameter;
                     if (!OCIBindByName($statement, ':clob' . $parameter, $descriptors[$clob_stream], -1, OCI_B_CLOB)) {
                         $success = $this->raiseError();
                         break;
                     }
                 }
                 if (!MDB2::isError($success)) {
                     for (reset($this->blobs[$prepared_query]), $blob = 0; $blob < count($this->blobs[$prepared_query]); $blob++, next($this->blobs[$prepared_query])) {
                         $blob_stream = key($this->blobs[$prepared_query]);
                         $parameter = $GLOBALS['_MDB2_LOBs'][$blob_stream]->parameter;
                         if (!OCIBindByName($statement, ':blob' . $parameter, $descriptors[$blob_stream], -1, OCI_B_BLOB)) {
                             $success = $this->raiseError();
                             break;
                         }
                     }
                 }
             }
             if (!MDB2::isError($success)) {
                 $mode = $lobs == 0 && $this->auto_commit ? OCI_COMMIT_ON_SUCCESS : OCI_DEFAULT;
                 $result = @OCIExecute($statement, $mode);
                 if ($result) {
                     if ($lobs) {
                         for (reset($this->clobs[$prepared_query]), $clob = 0; $clob < count($this->clobs[$prepared_query]); $clob++, next($this->clobs[$prepared_query])) {
                             $clob_stream = key($this->clobs[$prepared_query]);
                             for ($value = ''; !$this->datatype->endOfLOB($clob_stream);) {
                                 if ($this->datatype->readLOB($clob_stream, $data, $this->options['lob_buffer_length']) < 0) {
                                     $success = $this->raiseError();
                                     break;
                                 }
                                 $value .= $data;
                             }
                             if (!MDB2::isError($success) && !$descriptors[$clob_stream]->save($value)) {
                                 $success = $this->raiseError();
                             }
                         }
                         if (!MDB2::isError($success)) {
                             for (reset($this->blobs[$prepared_query]), $blob = 0; $blob < count($this->blobs[$prepared_query]); $blob++, next($this->blobs[$prepared_query])) {
                                 $blob_stream = key($this->blobs[$prepared_query]);
                                 for ($value = ''; !$this->datatype->endOfLOB($blob_stream);) {
                                     if ($this->datatype->readLOB($blob_stream, $data, $this->options['lob_buffer_length']) < 0) {
                                         $success = $this->raiseError();
                                         break;
                                     }
                                     $value .= $data;
                                 }
                                 if (!MDB2::isError($success) && !$descriptors[$blob_stream]->save($value)) {
                                     $success = $this->raiseError();
                                 }
                             }
                         }
                     }
                     if ($this->auto_commit) {
                         if ($lobs) {
                             if (MDB2::isError($success)) {
                                 if (!OCIRollback($this->connection)) {
                                     $success = $this->raiseError();
                                 }
                             } else {
                                 if (!OCICommit($this->connection)) {
                                     $success = $this->raiseError();
                                 }
                             }
                         }
                     } else {
                         ++$this->uncommitedqueries;
                     }
                     if (!MDB2::isError($success)) {
                         if (is_null($ismanip)) {
                             $ismanip = MDB2::isManip($query);
                         }
                         if ($ismanip) {
                             $this->affected_rows = @OCIRowCount($statement);
                             @OCIFreeCursor($statement);
                         }
                         $result = $statement;
                     }
                 } else {
                     return $this->raiseError($statement);
                 }
             }
         } else {
             return $this->raiseError();
         }
     }
     for (reset($descriptors), $descriptor = 0; $descriptor < count($descriptors); $descriptor++, next($descriptors)) {
         @$descriptors[key($descriptors)]->free();
     }
     if (MDB2::isError($success)) {
         return $success;
     }
     return $result;
 }
Esempio n. 15
0
 /**
  * all the RDBMS specific things needed close a DB connection
  * 
  * @access private
  */
 function _doQuery($query, $first = 0, $limit = 0, $prepared_query = 0)
 {
     $lobs = 0;
     $success = MDB_OK;
     $result = 0;
     $descriptors = array();
     if ($prepared_query) {
         $columns = '';
         $variables = '';
         for (reset($this->clobs[$prepared_query]), $clob = 0; $clob < count($this->clobs[$prepared_query]); $clob++, next($this->clobs[$prepared_query])) {
             $position = key($this->clobs[$prepared_query]);
             if (gettype($descriptors[$position] = @OCINewDescriptor($this->connection, OCI_D_LOB)) != 'object') {
                 $success = $this->raiseError(MDB_ERROR, NULL, NULL, 'Do query: Could not create descriptor for clob parameter');
                 break;
             }
             $columns .= ($lobs == 0 ? ' RETURNING ' : ',') . $this->prepared_queries[$prepared_query - 1]['Fields'][$position - 1];
             $variables .= ($lobs == 0 ? ' INTO ' : ',') . ':clob' . $position;
             $lobs++;
         }
         if (!MDB::isError($success)) {
             for (reset($this->blobs[$prepared_query]), $blob = 0; $blob < count($this->blobs[$prepared_query]); $blob++, next($this->blobs[$prepared_query])) {
                 $position = key($this->blobs[$prepared_query]);
                 if (gettype($descriptors[$position] = @OCINewDescriptor($this->connection, OCI_D_LOB)) != 'object') {
                     $success = $this->raiseError(MDB_ERROR, NULL, NULL, 'Do query: Could not create descriptor for blob parameter');
                     break;
                 }
                 $columns .= ($lobs == 0 ? ' RETURNING ' : ',') . $this->prepared_queries[$prepared_query - 1]['Fields'][$position - 1];
                 $variables .= ($lobs == 0 ? ' INTO ' : ',') . ':blob' . $position;
                 $lobs++;
             }
             $query .= $columns . $variables;
         }
     }
     if (!MDB::isError($success)) {
         if ($statement = @OCIParse($this->connection, $query)) {
             if ($lobs) {
                 for (reset($this->clobs[$prepared_query]), $clob = 0; $clob < count($this->clobs[$prepared_query]); $clob++, next($this->clobs[$prepared_query])) {
                     $position = key($this->clobs[$prepared_query]);
                     if (!@OCIBindByName($statement, ':clob' . $position, $descriptors[$position], -1, OCI_B_CLOB)) {
                         $success = $this->oci8RaiseError(NULL, 'Do query: Could not bind clob upload descriptor');
                         break;
                     }
                 }
                 if (!MDB::isError($success)) {
                     for (reset($this->blobs[$prepared_query]), $blob = 0; $blob < count($this->blobs[$prepared_query]); $blob++, next($this->blobs[$prepared_query])) {
                         $position = key($this->blobs[$prepared_query]);
                         if (!@OCIBindByName($statement, ':blob' . $position, $descriptors[$position], -1, OCI_B_BLOB)) {
                             $success = $this->oci8RaiseError(NULL, 'Do query: Could not bind blob upload descriptor');
                             break;
                         }
                     }
                 }
             }
             if (!MDB::isError($success)) {
                 if ($result = @OCIExecute($statement, $lobs == 0 && $this->auto_commit ? OCI_COMMIT_ON_SUCCESS : OCI_DEFAULT)) {
                     if ($lobs) {
                         for (reset($this->clobs[$prepared_query]), $clob = 0; $clob < count($this->clobs[$prepared_query]); $clob++, next($this->clobs[$prepared_query])) {
                             $position = key($this->clobs[$prepared_query]);
                             $clob_stream = $this->prepared_queries[$prepared_query - 1]['Values'][$position - 1];
                             for ($value = ''; !$this->endOfLOB($clob_stream);) {
                                 if ($this->readLOB($clob_stream, $data, $this->getOption('lob_buffer_length')) < 0) {
                                     $success = $this->raiseError();
                                     break;
                                 }
                                 $value .= $data;
                             }
                             if (!MDB::isError($success) && !$descriptors[$position]->save($value)) {
                                 $success = $this->oci8RaiseError(NULL, 'Do query: Could not upload clob data');
                             }
                         }
                         if (!MDB::isError($success)) {
                             for (reset($this->blobs[$prepared_query]), $blob = 0; $blob < count($this->blobs[$prepared_query]); $blob++, next($this->blobs[$prepared_query])) {
                                 $position = key($this->blobs[$prepared_query]);
                                 $blob_stream = $this->prepared_queries[$prepared_query - 1]['Values'][$position - 1];
                                 for ($value = ''; !$this->endOfLOB($blob_stream);) {
                                     if ($this->readLOB($blob_stream, $data, $this->getOption('lob_buffer_length')) < 0) {
                                         $success = $this->raiseError();
                                         break;
                                     }
                                     $value .= $data;
                                 }
                                 if (!MDB::isError($success) && !$descriptors[$position]->save($value)) {
                                     $success = $this->oci8RaiseError(NULL, 'Do query: Could not upload blob data');
                                 }
                             }
                         }
                     }
                     if ($this->auto_commit) {
                         if ($lobs) {
                             if (MDB::isError($success)) {
                                 if (!@OCIRollback($this->connection)) {
                                     $success = $this->oci8RaiseError(NULL, 'Do query: ' . $success->getUserinfo() . ' and then could not rollback LOB updating transaction');
                                 }
                             } else {
                                 if (!@OCICommit($this->connection)) {
                                     $success = $this->oci8RaiseError(NULL, 'Do query: Could not commit pending LOB updating transaction');
                                 }
                             }
                         }
                     } else {
                         $this->uncommitedqueries++;
                     }
                     if (!MDB::isError($success)) {
                         switch (@OCIStatementType($statement)) {
                             case 'SELECT':
                                 $result_value = intval($statement);
                                 $this->current_row[$result_value] = -1;
                                 if ($limit > 0) {
                                     $this->limits[$result_value] = array($first, $limit, 0);
                                 }
                                 $this->highest_fetched_row[$result_value] = -1;
                                 break;
                             default:
                                 $this->affected_rows = @OCIRowCount($statement);
                                 @OCIFreeCursor($statement);
                                 break;
                         }
                         $result = $statement;
                     }
                 } else {
                     return $this->oci8RaiseError($statement, 'Do query: Could not execute query');
                 }
             }
         } else {
             return $this->oci8RaiseError(NULL, 'Do query: Could not parse query');
         }
     }
     for (reset($descriptors), $descriptor = 0; $descriptor < count($descriptors); $descriptor++, next($descriptors)) {
         @OCIFreeDesc($descriptors[key($descriptors)]);
     }
     return $result;
 }
Esempio n. 16
0
 function _query($sql, $inputarr)
 {
     if (is_array($sql)) {
         // is prepared sql
         $stmt = $sql[1];
         // we try to bind to permanent array, so that OCIBindByName is persistent
         // and carried out once only - note that max array element size is 4000 chars
         if (is_array($inputarr)) {
             $bindpos = $sql[3];
             if (isset($this->_bind[$bindpos])) {
                 // all tied up already
                 $bindarr =& $this->_bind[$bindpos];
             } else {
                 // one statement to bind them all
                 $bindarr = array();
                 foreach ($inputarr as $k => $v) {
                     $bindarr[$k] = $v;
                     OCIBindByName($stmt, ":{$k}", $bindarr[$k], 4000);
                 }
                 $this->_bind[$bindpos] =& $bindarr;
             }
         }
     } else {
         $stmt = @OCIParse($this->_connectionID, $sql);
     }
     $this->_stmt = $stmt;
     if (!$stmt) {
         return false;
     }
     if (defined('ADODB_PREFETCH_ROWS')) {
         @OCISetPrefetch($stmt, ADODB_PREFETCH_ROWS);
     }
     if (is_array($inputarr)) {
         foreach ($inputarr as $k => $v) {
             if (is_array($v)) {
                 if (sizeof($v) == 2) {
                     // suggested by g.giunta@libero.
                     OCIBindByName($stmt, ":{$k}", $inputarr[$k][0], $v[1]);
                 } else {
                     OCIBindByName($stmt, ":{$k}", $inputarr[$k][0], $v[1], $v[2]);
                 }
             } else {
                 $len = -1;
                 if ($v === ' ') {
                     $len = 1;
                 }
                 if (isset($bindarr)) {
                     // is prepared sql, so no need to ocibindbyname again
                     $bindarr[$k] = $v;
                 } else {
                     // dynamic sql, so rebind every time
                     OCIBindByName($stmt, ":{$k}", $inputarr[$k], $len);
                 }
             }
         }
     }
     if (OCIExecute($stmt, $this->_commit)) {
         switch (@OCIStatementType($stmt)) {
             case "SELECT":
                 return $stmt;
             case "BEGIN":
                 if (isset($sql[4])) {
                     // jlim
                     $cursor = $sql[4];
                     // jlim
                     OCIExecute($cursor);
                     return $cursor;
                 } else {
                     return $stmt;
                 }
                 break;
             default:
                 return true;
         }
         /* Now this could be an Update/Insert or Delete */
         //if (@OCIStatementType($stmt) != 'SELECT') return true;
         //return $stmt;
     }
     return false;
 }
Esempio n. 17
0
 function DoQuery($query, $first = 0, $limit = 0, $prepared_query = 0)
 {
     $lobs = 0;
     $success = 1;
     $result = 0;
     $descriptors = array();
     if ($prepared_query) {
         $columns = "";
         $variables = "";
         for (Reset($this->clobs[$prepared_query]), $clob = 0; $clob < count($this->clobs[$prepared_query]); $clob++, Next($this->clobs[$prepared_query])) {
             $position = Key($this->clobs[$prepared_query]);
             if (GetType($descriptors[$position] = OCINewDescriptor($this->connection, OCI_D_LOB)) != "object") {
                 $this->SetError("Do query", "Could not create descriptor for clob parameter");
                 $success = 0;
                 break;
             }
             $columns .= ($lobs == 0 ? " RETURNING " : ",") . $this->prepared_queries[$prepared_query - 1]["Fields"][$position - 1];
             $variables .= ($lobs == 0 ? " INTO " : ",") . ":clob" . $position;
             $lobs++;
         }
         if ($success) {
             for (Reset($this->blobs[$prepared_query]), $blob = 0; $blob < count($this->blobs[$prepared_query]); $blob++, Next($this->blobs[$prepared_query])) {
                 $position = Key($this->blobs[$prepared_query]);
                 if (GetType($descriptors[$position] = OCINewDescriptor($this->connection, OCI_D_LOB)) != "object") {
                     $this->SetError("Do query", "Could not create descriptor for blob parameter");
                     $success = 0;
                     break;
                 }
                 $columns .= ($lobs == 0 ? " RETURNING " : ",") . $this->prepared_queries[$prepared_query - 1]["Fields"][$position - 1];
                 $variables .= ($lobs == 0 ? " INTO " : ",") . ":blob" . $position;
                 $lobs++;
             }
             $query .= $columns . $variables;
         }
     }
     if ($success) {
         if ($statement = OCIParse($this->connection, $query)) {
             if ($lobs) {
                 for (Reset($this->clobs[$prepared_query]), $clob = 0; $clob < count($this->clobs[$prepared_query]); $clob++, Next($this->clobs[$prepared_query])) {
                     $position = Key($this->clobs[$prepared_query]);
                     if (!OCIBindByName($statement, ":clob" . $position, $descriptors[$position], -1, OCI_B_CLOB)) {
                         $this->SetOCIError("Do query", "Could not bind clob upload descriptor", OCIError($statement));
                         $success = 0;
                         break;
                     }
                 }
                 if ($success) {
                     for (Reset($this->blobs[$prepared_query]), $blob = 0; $blob < count($this->blobs[$prepared_query]); $blob++, Next($this->blobs[$prepared_query])) {
                         $position = Key($this->blobs[$prepared_query]);
                         if (!OCIBindByName($statement, ":blob" . $position, $descriptors[$position], -1, OCI_B_BLOB)) {
                             $this->SetOCIError("Do query", "Could not bind blob upload descriptor", OCIError($statement));
                             $success = 0;
                             break;
                         }
                     }
                 }
             }
             if ($success) {
                 if ($result = @OCIExecute($statement, $lobs == 0 && $this->auto_commit ? OCI_COMMIT_ON_SUCCESS : OCI_DEFAULT)) {
                     if ($lobs) {
                         for (Reset($this->clobs[$prepared_query]), $clob = 0; $clob < count($this->clobs[$prepared_query]); $clob++, Next($this->clobs[$prepared_query])) {
                             $position = Key($this->clobs[$prepared_query]);
                             $clob_stream = $this->prepared_queries[$prepared_query - 1]["Values"][$position - 1];
                             for ($value = ""; !MetabaseEndOfLOB($clob_stream);) {
                                 if (MetabaseReadLOB($clob_stream, $data, $this->lob_buffer_length) < 0) {
                                     $this->SetError("Do query", MetabaseLOBError($clob));
                                     $success = 0;
                                     break;
                                 }
                                 $value .= $data;
                             }
                             if ($success && !$descriptors[$position]->save($value)) {
                                 $this->SetOCIError("Do query", "Could not upload clob data", OCIError($statement));
                                 $success = 0;
                             }
                         }
                         if ($success) {
                             for (Reset($this->blobs[$prepared_query]), $blob = 0; $blob < count($this->blobs[$prepared_query]); $blob++, Next($this->blobs[$prepared_query])) {
                                 $position = Key($this->blobs[$prepared_query]);
                                 $blob_stream = $this->prepared_queries[$prepared_query - 1]["Values"][$position - 1];
                                 for ($value = ""; !MetabaseEndOfLOB($blob_stream);) {
                                     if (MetabaseReadLOB($blob_stream, $data, $this->lob_buffer_length) < 0) {
                                         $this->SetError("Do query", MetabaseLOBError($blob));
                                         $success = 0;
                                         break;
                                     }
                                     $value .= $data;
                                 }
                                 if ($success && !$descriptors[$position]->save($value)) {
                                     $this->SetOCIError("Do query", "Could not upload blob data", OCIError($statement));
                                     $success = 0;
                                 }
                             }
                         }
                     }
                     if ($this->auto_commit) {
                         if ($lobs) {
                             if ($success) {
                                 if (!OCICommit($this->connection)) {
                                     $this->SetOCIError("Do query", "Could not commit pending LOB updating transaction", OCIError());
                                     $success = 0;
                                 }
                             } else {
                                 if (!OCIRollback($this->connection)) {
                                     $this->SetOCIError("Do query", $this->Error() . " and then could not rollback LOB updating transaction", OCIError());
                                 }
                             }
                         }
                     } else {
                         $this->uncommitedqueries++;
                     }
                     if ($success) {
                         switch (OCIStatementType($statement)) {
                             case "SELECT":
                                 $result_value = intval($statement);
                                 $this->current_row[$result_value] = -1;
                                 if ($limit > 0) {
                                     $this->limits[$result_value] = array($first, $limit, 0);
                                 }
                                 $this->highest_fetched_row[$result_value] = -1;
                                 break;
                             default:
                                 $this->affected_rows = OCIRowCount($statement);
                                 OCIFreeCursor($statement);
                                 break;
                         }
                         $result = $statement;
                     }
                 } else {
                     $this->SetOCIError("Do query", "Could not execute query", OCIError($statement));
                 }
             }
         } else {
             $this->SetOCIError("Do query", "Could not parse query", OCIError($statement));
         }
     }
     for (Reset($descriptors), $descriptor = 0; $descriptor < count($descriptors); $descriptor++, Next($descriptors)) {
         @OCIFreeDesc($descriptors[Key($descriptors)]);
     }
     return $result;
 }
Esempio n. 18
0
 /**
  * Execute a prepared query statement helper method.
  *
  * @param mixed $result_class string which specifies which result class to use
  * @param mixed $result_wrap_class string which specifies which class to wrap results in
  *
  * @return mixed MDB2_Result or integer (affected rows) on success,
  *               a MDB2 error on failure
  * @access private
  */
 function _execute($result_class = true, $result_wrap_class = false)
 {
     if (null === $this->statement) {
         return parent::_execute($result_class, $result_wrap_class);
     }
     $this->db->last_query = $this->query;
     $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
     if ($this->db->getOption('disable_query')) {
         $result = $this->is_manip ? 0 : null;
         return $result;
     }
     $connection = $this->db->getConnection();
     if (PEAR::isError($connection)) {
         return $connection;
     }
     $result = MDB2_OK;
     $lobs = $quoted_values = array();
     $i = 0;
     foreach ($this->positions as $parameter) {
         if (!array_key_exists($parameter, $this->values)) {
             return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null, 'Unable to bind to missing placeholder: ' . $parameter, __FUNCTION__);
         }
         $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
         if ($type == 'clob' || $type == 'blob') {
             $lobs[$i]['file'] = false;
             if (is_resource($this->values[$parameter])) {
                 $fp = $this->values[$parameter];
                 $this->values[$parameter] = '';
                 while (!feof($fp)) {
                     $this->values[$parameter] .= fread($fp, 8192);
                 }
             } elseif (is_a($this->values[$parameter], 'OCI-Lob')) {
                 //do nothing
             } elseif ($this->db->getOption('lob_allow_url_include') && preg_match('/^(\\w+:\\/\\/)(.*)$/', $this->values[$parameter], $match)) {
                 $lobs[$i]['file'] = true;
                 if ($match[1] == 'file://') {
                     $this->values[$parameter] = $match[2];
                 }
             }
             $lobs[$i]['value'] = $this->values[$parameter];
             $lobs[$i]['descriptor'] =& $this->values[$parameter];
             // Test to see if descriptor has already been created for this
             // variable (i.e. if it has been bound more than once):
             if (!is_a($this->values[$parameter], 'OCI-Lob')) {
                 $this->values[$parameter] = @OCINewDescriptor($connection, OCI_D_LOB);
                 if (false === $this->values[$parameter]) {
                     $result = $this->db->raiseError(null, null, null, 'Unable to create descriptor for LOB in parameter: ' . $parameter, __FUNCTION__);
                     break;
                 }
             }
             $lob_type = $type == 'blob' ? OCI_B_BLOB : OCI_B_CLOB;
             if (!@OCIBindByName($this->statement, ':' . $parameter, $lobs[$i]['descriptor'], -1, $lob_type)) {
                 $result = $this->db->raiseError($this->statement, null, null, 'could not bind LOB parameter', __FUNCTION__);
                 break;
             }
         } else {
             if ($type == OCI_B_BFILE) {
                 // Test to see if descriptor has already been created for this
                 // variable (i.e. if it has been bound more than once):
                 if (!is_a($this->values[$parameter], "OCI-Lob")) {
                     $this->values[$parameter] = @OCINewDescriptor($connection, OCI_D_FILE);
                     if (false === $this->values[$parameter]) {
                         $result = $this->db->raiseError(null, null, null, 'Unable to create descriptor for BFILE in parameter: ' . $parameter, __FUNCTION__);
                         break;
                     }
                 }
                 if (!@OCIBindByName($this->statement, ':' . $parameter, $this->values[$parameter], -1, $type)) {
                     $result = $this->db->raiseError($this->statement, null, null, 'Could not bind BFILE parameter', __FUNCTION__);
                     break;
                 }
             } else {
                 if ($type == OCI_B_ROWID) {
                     // Test to see if descriptor has already been created for this
                     // variable (i.e. if it has been bound more than once):
                     if (!is_a($this->values[$parameter], "OCI-Lob")) {
                         $this->values[$parameter] = @OCINewDescriptor($connection, OCI_D_ROWID);
                         if (false === $this->values[$parameter]) {
                             $result = $this->db->raiseError(null, null, null, 'Unable to create descriptor for ROWID in parameter: ' . $parameter, __FUNCTION__);
                             break;
                         }
                     }
                     if (!@OCIBindByName($this->statement, ':' . $parameter, $this->values[$parameter], -1, $type)) {
                         $result = $this->db->raiseError($this->statement, null, null, 'Could not bind ROWID parameter', __FUNCTION__);
                         break;
                     }
                 } else {
                     if ($type == OCI_B_CURSOR) {
                         // Test to see if cursor has already been allocated for this
                         // variable (i.e. if it has been bound more than once):
                         if (!is_resource($this->values[$parameter]) || !get_resource_type($this->values[$parameter]) == "oci8 statement") {
                             $this->values[$parameter] = @OCINewCursor($connection);
                             if (false === $this->values[$parameter]) {
                                 $result = $this->db->raiseError(null, null, null, 'Unable to allocate cursor for parameter: ' . $parameter, __FUNCTION__);
                                 break;
                             }
                         }
                         if (!@OCIBindByName($this->statement, ':' . $parameter, $this->values[$parameter], -1, $type)) {
                             $result = $this->db->raiseError($this->statement, null, null, 'Could not bind CURSOR parameter', __FUNCTION__);
                             break;
                         }
                     } else {
                         $maxlength = array_key_exists($parameter, $this->type_maxlengths) ? $this->type_maxlengths[$parameter] : -1;
                         $this->values[$parameter] = $this->db->quote($this->values[$parameter], $type, false);
                         $quoted_values[$i] =& $this->values[$parameter];
                         if (PEAR::isError($quoted_values[$i])) {
                             return $quoted_values[$i];
                         }
                         if (!@OCIBindByName($this->statement, ':' . $parameter, $quoted_values[$i], $maxlength)) {
                             $result = $this->db->raiseError($this->statement, null, null, 'could not bind non-abstract parameter', __FUNCTION__);
                             break;
                         }
                     }
                 }
             }
         }
         ++$i;
     }
     $lob_keys = array_keys($lobs);
     if (!PEAR::isError($result)) {
         $mode = !empty($lobs) || $this->db->in_transaction ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
         if (!@OCIExecute($this->statement, $mode)) {
             $err = $this->db->raiseError($this->statement, null, null, 'could not execute statement', __FUNCTION__);
             return $err;
         }
         if (!empty($lobs)) {
             foreach ($lob_keys as $i) {
                 if (null !== $lobs[$i]['value'] && $lobs[$i]['value'] !== '') {
                     if (is_object($lobs[$i]['value'])) {
                         // Probably a NULL LOB
                         // @see http://bugs.php.net/bug.php?id=27485
                         continue;
                     }
                     if ($lobs[$i]['file']) {
                         $result = $lobs[$i]['descriptor']->savefile($lobs[$i]['value']);
                     } else {
                         $result = $lobs[$i]['descriptor']->save($lobs[$i]['value']);
                     }
                     if (!$result) {
                         $result = $this->db->raiseError(null, null, null, 'Unable to save descriptor contents', __FUNCTION__);
                         break;
                     }
                 }
             }
             if (!PEAR::isError($result)) {
                 if (!$this->db->in_transaction) {
                     if (!@OCICommit($connection)) {
                         $result = $this->db->raiseError(null, null, null, 'Unable to commit transaction', __FUNCTION__);
                     }
                 } else {
                     ++$this->db->uncommitedqueries;
                 }
             }
         }
     }
     if (PEAR::isError($result)) {
         return $result;
     }
     if ($this->is_manip) {
         $affected_rows = $this->db->_affectedRows($connection, $this->statement);
         return $affected_rows;
     }
     $result = $this->db->_wrapResult($this->statement, $this->result_types, $result_class, $result_wrap_class, $this->limit, $this->offset);
     $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
     return $result;
 }
Esempio n. 19
0
function DBSaveLob($connection, $sql, $blobParamName, $data, $lobType)
{
    // Guarda datos en un clob..
    global $dbError;
    $lob = OCINewDescriptor($connection, OCI_D_LOB);
    $stmt = OCIParse($connection, $sql);
    OCIBindByName($stmt, ":" . $blobParamName, $lob, -1, $lobType);
    $error = !oci_execute($stmt, OCI_DEFAULT);
    $result = $lob->write($data);
    if ($result) {
        OCICommit($connection);
    }
    if ($error) {
        $dbError = oci_error($stmt);
        if (isset($dbError["offset"])) {
            throw new Exception($dbError["message"]);
        }
    }
    return $result;
}
Esempio n. 20
0
 /**
  * Execute an SQL query with blob fields processing
  * @param String sql
  * @param Array blobs
  * @param Array blobTypes
  * @return Boolean
  */
 public function execWithBlobProcessing($sql, $blobs, $blobTypes = array())
 {
     set_error_handler("empty_error_handler");
     $locs = array();
     if (count($blobs)) {
         $idx = 1;
         $sql .= " returning ";
         $blobfields = "";
         $blobvars = "";
         foreach ($blobs as $ekey => $value) {
             if (count($locs)) {
                 $blobfields .= ",";
                 $blobvars .= ",";
             }
             $blobfields .= $ekey;
             $blobvars .= ":bnd" . $idx;
             $locs[$ekey] = OCINewDescriptor($this->conn, OCI_D_LOB);
             $idx++;
         }
         $sql .= $blobfields . " into " . $blobvars;
     }
     $stmt = OCIParse($this->conn, $sql);
     $idx = 1;
     foreach ($locs as $ekey => $value) {
         OCIBindByName($stmt, ":bnd" . $idx, $locs[$ekey], -1, OCI_B_BLOB);
         $idx++;
     }
     $result = OCIExecute($stmt, OCI_DEFAULT) !== false;
     foreach ($locs as $ekey => $value) {
         $locs[$ekey]->save($blobs[$ekey]);
         $locs[$ekey]->free();
     }
     OCICommit($this->conn);
     OCIFreeStatement($stmt);
     set_error_handler("runner_error_handler");
     return $result;
 }
Esempio n. 21
0
 /**
  * Executes a DB statement prepared with prepare().
  *
  * @param $stmt a DB statement resource (returned from prepare())
  * @param $data data to be used in execution of the statement
  *
  * @return int returns an oci8 result resource for successful
  * SELECT queries, DB_OK for other successful queries.  A DB error
  * code is returned on failure.
  */
 function execute($stmt, $data = false)
 {
     $types =& $this->prepare_types[$stmt];
     if (($size = sizeof($types)) != sizeof($data)) {
         return $this->raiseError(DB_ERROR_MISMATCH);
     }
     for ($i = 0; $i < $size; $i++) {
         if (is_array($data)) {
             $pdata[$i] =& $data[$i];
         } else {
             $pdata[$i] =& $data;
         }
         if ($types[$i] == DB_PARAM_OPAQUE) {
             $fp = fopen($pdata[$i], "r");
             $pdata[$i] = '';
             if ($fp) {
                 while (($buf = fread($fp, 4096)) != false) {
                     $pdata[$i] .= $buf;
                 }
             }
         }
         if (!@OCIBindByName($stmt, ":bind" . $i, $pdata[$i], -1)) {
             return $this->oci8RaiseError($stmt);
         }
     }
     if ($this->autoCommit) {
         $success = @OCIExecute($stmt, OCI_COMMIT_ON_SUCCESS);
     } else {
         $success = @OCIExecute($stmt, OCI_DEFAULT);
     }
     if (!$success) {
         return $this->oci8RaiseError($stmt);
     }
     $this->last_stmt = $stmt;
     if ($this->manip_query[(int) $stmt]) {
         return DB_OK;
     } else {
         return new DB_result($this, $stmt);
     }
 }
Esempio n. 22
0
     $r = OCIExecute($parsed, OCI_DEFAULT);
     if (!$r) {
         $e = oci_error($parsed);
         echo htmlentities($e['message']);
         exit;
     }
     //$cmdstr2 =  "insert into ownedby (item_seq.currval, :bind3)";
     $cmdstr2 = "insert into ownedby values (item_seq.currval, :bind3)";
     echo $cmdstr2;
     $parsed2 = OCIParse($db_conn, $cmdstr2);
     if (!$parsed2) {
         $e = OCIError($db_conn);
         echo htmlentities($e['message']);
         exit;
     }
     OCIBindByName($parsed2, ":bind3", $owner);
     $r = OCIExecute($parsed2, OCI_DEFAULT);
     if (!$r) {
         $e = oci_error($parsed2);
         echo htmlentities($e['message']);
         exit;
     }
 } else {
     echo "<br>input invalid value.<br>";
 }
 // Select data...
 //$cmdstr = "select i.inumber, i.value, i.description, o.email from item i, ownedby i where i.i_number=o.i_number";
 $cmdstr = "select i.i_number, i.value, i.description, o.email \r\n\t\tfrom item i, ownedby o \r\n\t\twhere i.i_number=o.i_number\r\n\t\torder by i.i_number desc";
 echo $cmdstr;
 $parsed = OCIParse($db_conn, $cmdstr);
 if (!$parsed) {
Esempio n. 23
0
 public function write($id, $data)
 {
     $query = "MERGE INTO " . self::$_table["saveHandler"]["options"]["name"] . " M ";
     $query .= "USING (SELECT '" . $id . "' AS ID, :TIME AS LIFETIME, :DADOS AS DATAVAL FROM DUAL) N ";
     $query .= "ON (M." . self::$_table["saveHandler"]["options"]["primary"][0] . " = N.ID ) ";
     $query .= "WHEN MATCHED THEN ";
     $query .= "UPDATE SET M." . self::$_table["saveHandler"]["options"]["lifetimeColumn"] . " = N.LIFETIME, ";
     $query .= "M." . self::$_table["saveHandler"]["options"]["dataColumn"] . " = N.DATAVAL ";
     $query .= "WHEN NOT MATCHED THEN INSERT( " . self::$_table["saveHandler"]["options"]["primary"][0] . ", ";
     $query .= self::$_table["saveHandler"]["options"]["lifetimeColumn"] . ", ";
     $query .= self::$_table["saveHandler"]["options"]["dataColumn"] . " ) ";
     $query .= "VALUES(N.ID, N.LIFETIME, N.DATAVAL) ";
     $stmt = OCIParse(self::$_db, $query);
     $clob = OCINewDescriptor(self::$_db, OCI_D_LOB);
     OCIBindByName($stmt, ':TIME', time());
     OCIBindByName($stmt, ':DADOS', $clob, -1, OCI_B_CLOB);
     $clob->WriteTemporary($data, OCI_TEMP_CLOB);
     $exe = OCIExecute($stmt, OCI_DEFAULT);
     if ($exe === true) {
         $ret = true;
         OCICommit(self::$_db);
     } else {
         $ret = false;
         OCIRollback(self::$_db);
     }
     $clob->close();
     $clob->free();
     OCIFreeStatement($stmt);
     return $ret;
 }
Esempio n. 24
0
       parsed once. */
    $cmdstr = "insert into tab1 values (:bind1, :bind2)";
    //define two bind variables in the SQL statement.
    $parsed = OCIParse($db_conn, $cmdstr);
    // parse the statement
    if (!$parsed) {
        $e = OCIError($db_conn);
        echo htmlentities($e['message']);
        exit;
    }
    $var1 = 2;
    $var2 = "Scott";
    // define two PHP variables
    OCIBindByName($parsed, ":bind1", $var1);
    // bind the PHP variables "$var1" to ":bind1"
    OCIBindByName($parsed, ":bind2", $var2);
    $r = OCIExecute($parsed, OCI_DEFAULT);
    if (!$r) {
        $e = oci_error($parsed);
        echo htmlentities($e['message']);
        exit;
    }
    //Insert data got from user...
    echo "Please insert test data:<br>";
    ?>
 

<p><font size="2"> Number&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Name</font></p>
<form method="POST" action="oracle-test2.php">
<!--go to "oracle-text2.php" when submit-->
 function _query($sql, $inputarr)
 {
     if (is_array($sql)) {
         // is prepared sql
         $stmt = $sql[1];
         // we try to bind to permanent array, so that OCIBindByName is persistent
         // and carried out once only - note that max array element size is 4000 chars
         if (is_array($inputarr)) {
             $bindpos = $sql[3];
             if (isset($this->_bind[$bindpos])) {
                 // all tied up already
                 $bindarr =& $this->_bind[$bindpos];
             } else {
                 // one statement to bind them all
                 $bindarr = array();
                 foreach ($inputarr as $k => $v) {
                     $bindarr[$k] = $v;
                     OCIBindByName($stmt, ":{$k}", $bindarr[$k], 4000);
                 }
                 $this->_bind[$bindpos] =& $bindarr;
             }
         }
     } else {
         $stmt = OCIParse($this->_connectionID, $sql);
     }
     $this->_stmt = $stmt;
     if (!$stmt) {
         return false;
     }
     if (defined('ADODB_PREFETCH_ROWS')) {
         @OCISetPrefetch($stmt, ADODB_PREFETCH_ROWS);
     }
     if (is_array($inputarr)) {
         foreach ($inputarr as $k => $v) {
             if (is_array($v)) {
                 if (sizeof($v) == 2) {
                     // suggested by g.giunta@libero.
                     OCIBindByName($stmt, ":{$k}", $inputarr[$k][0], $v[1]);
                 } else {
                     OCIBindByName($stmt, ":{$k}", $inputarr[$k][0], $v[1], $v[2]);
                 }
                 if ($this->debug == 99) {
                     echo "name=:{$k}", ' var=' . $inputarr[$k][0], ' len=' . $v[1], ' type=' . $v[2], '<br>';
                 }
             } else {
                 $len = -1;
                 if ($v === ' ') {
                     $len = 1;
                 }
                 if (isset($bindarr)) {
                     // is prepared sql, so no need to ocibindbyname again
                     $bindarr[$k] = $v;
                 } else {
                     // dynamic sql, so rebind every time
                     OCIBindByName($stmt, ":{$k}", $inputarr[$k], $len);
                 }
             }
         }
     }
     $this->_errorMsg = false;
     $this->_errorCode = false;
     if (OCIExecute($stmt, $this->_commit)) {
         switch (@OCIStatementType($stmt)) {
             case "SELECT":
                 return $stmt;
             case "BEGIN":
                 if (is_array($sql) && !empty($sql[4])) {
                     $cursor = $sql[4];
                     if (is_resource($cursor)) {
                         $ok = OCIExecute($cursor);
                         return $cursor;
                     }
                     return $stmt;
                 } else {
                     if (is_resource($stmt)) {
                         OCIFreeStatement($stmt);
                         return true;
                     }
                     return $stmt;
                 }
                 break;
             default:
                 // ociclose -- no because it could be used in a LOB?
                 return true;
         }
     }
     return false;
 }
Esempio n. 26
0
 echo "owner= ";
 echo $owner;
 echo "descr= ";
 echo $descr;
 if ($value && $owner) {
     $cmdstr = "insert into item(value,description) values (:bind1, :bind2)";
     // $cmdstr = $cmdstr . "insert into item(value,description) values (:bind1, :bind2)";
     echo $cmdstr;
     $parsed = OCIParse($db_conn, $cmdstr);
     if (!$parsed) {
         $e = OCIError($db_conn);
         echo htmlentities($e['message']);
         exit;
     }
     OCIBindByName($parsed, ":bind1", $value);
     OCIBindByName($parsed, ":bind2", $descr);
     $r = OCIExecute($parsed, OCI_DEFAULT);
     if (!$r) {
         $e = oci_error($parsed);
         echo htmlentities($e['message']);
         exit;
     }
 } else {
     echo "<br>input invalid value.<br>";
 }
 // Select data...
 $cmdstr = "select * from item";
 echo $cmdstr;
 $parsed = OCIParse($db_conn, $cmdstr);
 if (!$parsed) {
     $e = OCIError($db_conn);
Esempio n. 27
0
 /**
  * @name registro_db
  * @param string cadena_sql 
  * @param int numero
  * @return boolean
  * @access public
  */
 function registro_db($cadena_sql, $numero)
 {
     unset($this->registro);
     if (!is_resource($this->enlace)) {
         return FALSE;
     }
     $cadenaParser = OCIParse($this->enlace, $cadena_sql);
     if (isset($this->variable_sql)) {
         OCIBindByName($cadenaParser, $this->variable_sql[0], $salidaSQL, $this->variable_sql[1]);
     }
     $busqueda = OCIExecute($cadenaParser);
     $this->afectadas = oci_num_rows($cadenaParser);
     if ($busqueda) {
         $j = 0;
         while (OCIFetchInto($cadenaParser, $row, OCI_RETURN_NULLS)) {
             $a = 0;
             $un_campo = 0;
             $campos = count($row);
             while ($a < $campos) {
                 $this->registro[$j][$un_campo] = $row[$a++];
                 $un_campo++;
             }
             $j++;
             //$this->registro[$j][$un_campo] = $salida[$j][$un_campo];
         }
         if (isset($salidaSQL)) {
             $this->registro[0][0] = $salidaSQL;
             $j = 1;
             unset($this->variable_sql);
         }
         $this->conteo = $j--;
         @OCIFreeCursor($cadenaParser);
         return $this->conteo;
     } else {
         unset($this->registro);
         $this->error = oci_error();
         return 0;
     }
 }
Esempio n. 28
0
 function query($Query_String)
 {
     /* No empty queries, please, since PHP4 chokes on them. */
     if ($Query_String == "") {
         /* The empty query string is passed on from the constructor,
          * when calling the class without a query, e.g. in situations
          * like these: '$db = new DB_Sql_Subclass;'
          */
         return 0;
     }
     $this->connect();
     $this->Query_ID = OCIParse($this->Link_ID, $Query_String);
     if (!$this->Query_ID) {
         $this->Error = OCIError($this->Query_ID);
         $this->Halt($this->Error);
     } else {
         $old_error_reporting = error_reporting();
         error_reporting($old_error_reporting & ~E_WARNING);
         if (sizeof($this->Binds) > 0) {
             foreach ($this->Binds as $parameter_name => $parameter_values) {
                 if ($parameter_values[2] == OCI_B_CURSOR) {
                     $this->Binds[$parameter_name][0] = OCINewCursor($this->Link_ID);
                 }
                 if ($parameter_values[2] == 0) {
                     OCIBindByName($this->Query_ID, ":" . $parameter_name, $this->Binds[$parameter_name][0], $parameter_values[1]);
                 } else {
                     OCIBindByName($this->Query_ID, ":" . $parameter_name, $this->Binds[$parameter_name][0], $parameter_values[1], $parameter_values[2]);
                 }
             }
         }
         OCIExecute($this->Query_ID);
         error_reporting($old_error_reporting);
         $this->Error = OCIError($this->Query_ID);
     }
     $this->Row = 0;
     if ($this->Debug) {
         printf("Debug: query = %s<br>\n", $Query_String);
     }
     if ($this->Error["code"] != 0 && $this->sqoe) {
         $this->Halt($this->Error);
     }
     #echo "<BR><FONT color=red><B>".$this->Error["message"]."<BR>Query :\"$Query_String\"</B></FONT>";
     if (sizeof($this->Binds) > 0) {
         $bi = 0;
         foreach ($this->Binds as $parameter_name => $parameter_values) {
             if ($parameter_values[2] == OCI_B_CURSOR) {
                 OCIExecute($this->Binds[$parameter_name][0]);
                 $this->Error = OCIError($this->Binds[$parameter_name][0]);
                 $this->Query_ID = $this->Binds[$parameter_name][0];
             }
             $this->Record[$parameter_name] = $parameter_values[0];
             $this->Record[$bi++] = $parameter_values[0];
         }
         $this->Binds = array();
     }
     return $this->Query_ID;
 }
	function _query($sql,$inputarr)
	{
		if (is_array($sql)) { // is prepared sql
			$stmt = $sql[1];

			// we try to bind to permanent array, so that OCIBindByName is persistent
			// and carried out once only - note that max array element size is 4000 chars
			if (is_array($inputarr)) {
				$bindpos = $sql[3];
				if (isset($this->_bind[$bindpos])) {
				// all tied up already
					$bindarr = $this->_bind[$bindpos];
				} else {
				// one statement to bind them all
					$bindarr = array();
					foreach($inputarr as $k => $v) {
						$bindarr[$k] = $v;
						OCIBindByName($stmt,":$k",$bindarr[$k],is_string($v) && strlen($v)>4000 ? -1 : 4000);
					}
					$this->_bind[$bindpos] = $bindarr;
				}
			}
		} else {
			$stmt=OCIParse($this->_connectionID,$sql);
		}

		$this->_stmt = $stmt;
		if (!$stmt) return false;

		if (defined('ADODB_PREFETCH_ROWS')) @OCISetPrefetch($stmt,ADODB_PREFETCH_ROWS);

		if (is_array($inputarr)) {
			foreach($inputarr as $k => $v) {
				if (is_array($v)) {
					if (sizeof($v) == 2) // suggested by g.giunta@libero.
						OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1]);
					else
						OCIBindByName($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]);

					if ($this->debug==99) {
						if (is_object($v[0]))
							echo "name=:$k",' len='.$v[1],' type='.$v[2],'<br>';
						else
							echo "name=:$k",' var='.$inputarr[$k][0],' len='.$v[1],' type='.$v[2],'<br>';

					}
				} else {
					$len = -1;
					if ($v === ' ') $len = 1;
					if (isset($bindarr)) {	// is prepared sql, so no need to ocibindbyname again
						$bindarr[$k] = $v;
					} else { 				// dynamic sql, so rebind every time
						OCIBindByName($stmt,":$k",$inputarr[$k],$len);
					}
				}
			}
		}

        $this->_errorMsg = false;
		$this->_errorCode = false;
		if (OCIExecute($stmt,$this->_commit)) {
//OCIInternalDebug(1);
			if (count($this -> _refLOBs) > 0) {

				foreach ($this -> _refLOBs as $key => $value) {
					if ($this -> _refLOBs[$key]['TYPE'] == true) {
						$tmp = $this -> _refLOBs[$key]['LOB'] -> load();
						if ($this -> debug) {
							ADOConnection::outp("<b>OUT LOB</b>: LOB has been loaded. <br>");
						}
						//$_GLOBALS[$this -> _refLOBs[$key]['VAR']] = $tmp;
						$this -> _refLOBs[$key]['VAR'] = $tmp;
					} else {
                        $this->_refLOBs[$key]['LOB']->save($this->_refLOBs[$key]['VAR']);
						$this -> _refLOBs[$key]['LOB']->free();
						unset($this -> _refLOBs[$key]);
                        if ($this->debug) {
							ADOConnection::outp("<b>IN LOB</b>: LOB has been saved. <br>");
						}
                    }
				}
			}

            switch (@OCIStatementType($stmt)) {
                case "SELECT":
					return $stmt;

				case 'DECLARE':
                case "BEGIN":
                    if (is_array($sql) && !empty($sql[4])) {
						$cursor = $sql[4];
						if (is_resource($cursor)) {
							$ok = OCIExecute($cursor);
	                        return $cursor;
						}
						return $stmt;
                    } else {
						if (is_resource($stmt)) {
							OCIFreeStatement($stmt);
							return true;
						}
                        return $stmt;
                    }
                    break;
                default :
					// ociclose -- no because it could be used in a LOB?
                    return true;
            }
		}
		return false;
	}
 function &_doQuery($queryString)
 {
     if (strlen($queryString) > 3900) {
         if (preg_match('/^\\s*insert/i', $queryString)) {
             $queryString = preg_replace("/,(\\s*)''(\\s*)/U", ",\$1_double___getMeMadIfYouHaveThisValueInHere_\$2", $queryString);
             preg_match_all("|'(.*)[^']'{1}\\s*[,\\)]|Us", $queryString, $matches);
             $i = 0;
             $j = 0;
             while ($matches[1][$j]) {
                 $toReplace = substr($matches[0][$j], 0, strlen($matches[0][$j]) - 1);
                 $string = substr($matches[0][$j], 1, strlen($matches[0][$j]) - 3);
                 if (strlen($string) > 3900) {
                     $arReplace[$i] = $string;
                     $queryString = str_replace($toReplace, ':v_' . $i, $queryString);
                     $i++;
                 }
                 $j++;
             }
             $queryString = str_replace("_double___getMeMadIfYouHaveThisValueInHere_", "''", $queryString);
         } elseif (preg_match('/^\\s*update/i', $queryString)) {
             //on récupère pour analyse tout ce qui se trouve avant le where
             if (($pos = strrpos($queryString, 'where')) != false) {
                 $beforeWhere = substr($queryString, 0, $pos);
             } else {
                 $beforeWhere = $queryString;
             }
             //parcoure de la chaine pour trouver les chaine contenant les champs mis à jour
             $length = strlen($beforeWhere);
             $beginPos = null;
             $endPos = null;
             $matches = array();
             for ($j = 0; $j < $length; $j++) {
                 if ($beforeWhere[$j] === "'" && $beforeWhere[$j - 1] !== "'" && $beforeWhere[$j + 1] !== "'") {
                     if ($beginPos == null) {
                         $beginPos = $j;
                     } elseif ($endPos == null) {
                         $endPos = $j;
                     } else {
                         $matches[] = substr($beforeWhere, $beginPos, $endPos - $beginPos + 1);
                         $beginPos = $j;
                         $endPos = null;
                     }
                 }
             }
             if ($beginPos != null && $endPos != null) {
                 $matches[] = substr($beforeWhere, $beginPos, $endPos - $beginPos + 1);
             }
             $i = 0;
             foreach ($matches as $elem) {
                 $toReplace = substr($elem, 0, strlen($elem));
                 $string = substr($elem, 1, strlen($elem) - 2);
                 if (strlen($string) > 3900) {
                     $arReplace[$i] = $string;
                     $queryString = str_replace($toReplace, ':v_' . $i, $queryString);
                     $i++;
                 }
             }
         }
     }
     $stmt = ociparse($this->_connection, $queryString);
     if (is_array($arReplace)) {
         foreach ($arReplace as $key => $elem) {
             $elem = str_replace("_double___getMeMadIfYouHaveThisValueInHere_", "''", $elem);
             $elem = $this->_unquote($elem);
             OCIBindByName($stmt, ":v_" . $key, $elem, -1);
         }
     }
     if ($stmt && ociexecute($stmt)) {
         $rs =& new CopixDbResultSetOci8($stmt);
         $rs->_connector =& $this;
     } else {
         $rs = false;
     }
     return $rs;
 }