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();
 }
Example #2
0
 function query($sql)
 {
     $query = OCIParse($this->conn, $sql);
     OCIExecute($query);
     OCIcommit($this->conn);
     return $query;
 }
Example #3
0
 function executePlainSQL($cmdstr)
 {
     //takes a plain (no bound variables) SQL command and executes it
     //echo "<br>running ".$cmdstr."<br>";
     global $db_conn, $success;
     $statement = OCIParse($db_conn, $cmdstr);
     //There is a set of comments at the end of the file that describe some of the OCI specific functions and how they work
     if (!$statement) {
         echo "<br>Cannot parse the following command: " . $cmdstr . "<br>";
         $e = OCI_Error($db_conn);
         // For OCIParse errors pass the
         // connection handle
         echo htmlentities($e['message']);
         $success = False;
     }
     $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']);
         $success = False;
     } else {
     }
     return $statement;
 }
Example #4
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;
        }
    }
}
Example #5
0
 function num_rows($query, $sql)
 {
     $sql = "select Count(*) NUM from ({$sql})";
     $query = OCIParse($this->conn, $sql);
     OCIExecute($query);
     ocifetchinto($query, $row, OCI_BOTH);
     return $row[NUM];
 }
function da_sql_num_rows($statement, $config)
{
    // Unfortunately we need to fetch the statement as ocirowcount doesn't work on SELECTs
    $rows = OCIFetchStatement($statement, $res);
    if ($config[sql_debug] == 'true') {
        print "<b>DEBUG(SQL,OCI DRIVER): Query Result: Num rows:: " . $rows . "</b><br>\n";
    }
    // Unfortunately we need to re-execute because the statement cursor is reset after OCIFetchStatement :-(
    OCIExecute($statement);
    return $rows;
}
Example #7
0
 public function execQuery($name, $query)
 {
     if ($GLOBALS['DB_DEBUG']) {
         echo $query . '<br>';
     }
     if ($this->connection) {
         $this->freeResult($name);
         $this->result[$name] = OCIParse($this->connection, $query);
         OCIExecute($this->result[$name]);
         return $this->result[$name];
     }
 }
Example #8
0
 function GetInformations()
 {
     //    $query = "select log_nom,log_prenom,log_fonction,log_fonctions, log_equipes,log_uf,log_uid from hopi.log where log_idsession = ".$this->hopisession ;
     $query = "select * from hopi.log where log_idsession = " . $this->hopisession;
     if (function_exists('OCILogon')) {
         $conn = @OCILogon("hopi", "hopi", "hopi");
         $stmt = @OCIParse($conn, $query);
         @OCIExecute($stmt);
         $nrows = @OCIFetchStatement($stmt, $results);
         $ldap = new clAuthLdap();
         if ($nrows > 0) {
             $_POST['login'] = $results["LOG_UID"][0];
             $ldap->valide('noBind');
             $_SESSION['hopisession'] = '';
             return $ldap->getInformations();
         }
         /*
         if ( $nrows > 0 ) {
           $log[uid] = $results["LOG_UID"][0] ;
         
           $log[nom] = $results["LOG_NOM"][0] ;
           $log[prenom] = $results["LOG_PRENOM"][0] ;
           $log[fonction] = $results["LOG_FONCTION"][0] ;
           $log[fonctions] = explode ( ',', $results["LOG_FONCTIONS"][0] ) ;
           $log[equipes] = explode ( ',', $results["LOG_EQUIPES"][0] ) ;
           $log[uf] = $results["LOG_UF"][0] ;
         	$log[org] = $results["LOG_ORGANISATION"][0] ;
         } else { $log = "false" ; }
         $infos[type]   = "Hopi" ;
         $infos[nom]    = $log[nom] ;
         $infos[prenom] = $log[prenom] ;
         $infos[iduser] = $log[uid] ;
         $infos[pseudo] = "Hopi (".$log[uid].")" ;
         $infos[mail]   = $log[uid]."@ch-hyeres.fr" ;
         $infos[uf]     = explode ( ",", str_ireplace ( "'", '', $results["LOG_UF"][0] ) ) ;
         $infos[org]    = $log[org] ;
         
         // Récupération de la liste des groupes.
         for ( $i = 0 ; isset ( $log[equipes][$i] ) ; $i++ ) $or_equipes .= " OR nomgroupe='".$log[equipes][$i]."'" ;
         for ( $i = 0 ; isset ( $log[fonctions][$i] ) ; $i++ ) $or_fonctions .= " OR nomgroupe='".$log[fonctions][$i]."'" ;
         $param[cw] = "where nomgroupe='HOPI' OR nomgroupe='".$log[uid]."' OR nomgroupe='".$log[fonction]."' $or_equipes $or_fonctions" ;
         $req = new clResultQuery ;
         $res = $req -> Execute ( "Fichier", "getGroupes", $param, "ResultQuery" ) ;
         $infos[idgroupe] = $res[idgroupe][0] ;
         for ( $j = 1 ; isset ( $res[idgroupe][$j] ) ; $j++ ) {
           $infos[idgroupe] .= ",".$res[idgroupe][$j] ;
         }
         //print "<br>Groupe(s) : ".$infos[idgroupe] ;
         */
         @oci_close($conn);
         return $infos;
     }
 }
Example #9
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;
}
Example #10
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;
}
Example #11
0
 /**
  * Performs an SQL query.
  *
  * @param  string  $query
  * @param  mixed   $limit
  * @param  boolean $warnOnFailure
  * @access public
  */
 function query($query, $limit = false, $warnOnFailure = true)
 {
     if ($limit != false) {
         $query = sprintf('SELECT * FROM (%s) WHERE ROWNUM <= %d', $query, $limit);
     }
     if ($this->config['debug_level'] > 1) {
         $this->debugQuery($query);
     }
     @OCIFreeStatement($this->result);
     $this->result = @OCIParse($this->connection, $query);
     if (!$this->result) {
         $error = OCIError($this->result);
         phpOpenTracker::handleError($error['code'] . $error['message'], E_USER_ERROR);
     }
     @OCIExecute($this->result);
     if (!$this->result && $warnOnFailure) {
         $error = OCIError($this->result);
         phpOpenTracker::handleError($error['code'] . $error['message'], E_USER_ERROR);
     }
 }
 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;
 }
Example #13
0
 function tableInfo($result, $mode = null)
 {
     $count = 0;
     $res = array();
     /*
      * depending on $mode, metadata returns the following values:
      *
      * - mode is false (default):
      * $res[]:
      *   [0]["table"]       table name
      *   [0]["name"]        field name
      *   [0]["type"]        field type
      *   [0]["len"]         field length
      *   [0]["nullable"]    field can be null (boolean)
      *   [0]["format"]      field precision if NUMBER
      *   [0]["default"]     field default value
      *
      * - mode is DB_TABLEINFO_ORDER
      * $res[]:
      *   ["num_fields"]     number of fields
      *   [0]["table"]       table name
      *   [0]["name"]        field name
      *   [0]["type"]        field type
      *   [0]["len"]         field length
      *   [0]["nullable"]    field can be null (boolean)
      *   [0]["format"]      field precision if NUMBER
      *   [0]["default"]     field default value
      *   ['order'][field name] index of field named "field name"
      *   The last one is used, if you have a field name, but no index.
      *   Test:  if (isset($result['order']['myfield'])) { ...
      *
      * - mode is DB_TABLEINFO_ORDERTABLE
      *    the same as above. but additionally
      *   ["ordertable"][table name][field name] index of field
      *      named "field name"
      *
      *      this is, because if you have fields from different
      *      tables with the same field name * they override each
      *      other with DB_TABLEINFO_ORDER
      *
      *      you can combine DB_TABLEINFO_ORDER and
      *      DB_TABLEINFO_ORDERTABLE with DB_TABLEINFO_ORDER |
      *      DB_TABLEINFO_ORDERTABLE * or with DB_TABLEINFO_FULL
      */
     // if $result is a string, we collect info for a table only
     if (is_string($result)) {
         $result = strtoupper($result);
         $q_fields = "select column_name, data_type, data_length, data_precision,\n                         nullable, data_default from user_tab_columns\n                         where table_name='{$result}' order by column_id";
         if (!($stmt = OCIParse($this->connection, $q_fields))) {
             return $this->oci8RaiseError();
         }
         if (!OCIExecute($stmt, OCI_DEFAULT)) {
             return $this->oci8RaiseError($stmt);
         }
         while (OCIFetch($stmt)) {
             $res[$count]['table'] = $result;
             $res[$count]['name'] = @OCIResult($stmt, 1);
             $res[$count]['type'] = @OCIResult($stmt, 2);
             $res[$count]['len'] = @OCIResult($stmt, 3);
             $res[$count]['format'] = @OCIResult($stmt, 4);
             $res[$count]['nullable'] = @OCIResult($stmt, 5) == 'Y' ? true : false;
             $res[$count]['default'] = @OCIResult($stmt, 6);
             if ($mode & DB_TABLEINFO_ORDER) {
                 $res['order'][$res[$count]['name']] = $count;
             }
             if ($mode & DB_TABLEINFO_ORDERTABLE) {
                 $res['ordertable'][$res[$count]['table']][$res[$count]['name']] = $count;
             }
             $count++;
         }
         $res['num_fields'] = $count;
         @OCIFreeStatement($stmt);
     } else {
         // else we want information about a resultset
         if ($result === $this->last_stmt) {
             $count = @OCINumCols($result);
             for ($i = 0; $i < $count; $i++) {
                 $res[$i]['name'] = @OCIColumnName($result, $i + 1);
                 $res[$i]['type'] = @OCIColumnType($result, $i + 1);
                 $res[$i]['len'] = @OCIColumnSize($result, $i + 1);
                 $q_fields = "select table_name, data_precision, nullable, data_default from user_tab_columns where column_name='" . $res[$i]['name'] . "'";
                 if (!($stmt = OCIParse($this->connection, $q_fields))) {
                     return $this->oci8RaiseError();
                 }
                 if (!OCIExecute($stmt, OCI_DEFAULT)) {
                     return $this->oci8RaiseError($stmt);
                 }
                 OCIFetch($stmt);
                 $res[$i]['table'] = OCIResult($stmt, 1);
                 $res[$i]['format'] = OCIResult($stmt, 2);
                 $res[$i]['nullable'] = OCIResult($stmt, 3) == 'Y' ? true : false;
                 $res[$i]['default'] = OCIResult($stmt, 4);
                 OCIFreeStatement($stmt);
                 if ($mode & DB_TABLEINFO_ORDER) {
                     $res['order'][$res[$i]['name']] = $i;
                 }
                 if ($mode & DB_TABLEINFO_ORDERTABLE) {
                     $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
                 }
             }
             $res['num_fields'] = $count;
         } else {
             return $this->raiseError(DB_ERROR_NOT_CAPABLE);
         }
     }
     return $res;
 }
Example #14
0
/**
 * Executes a SQL query.
 *
 * <b>Note:</b> Use the {@link dbi_error()} function to get error information
 * if the connection fails.
 *
 * @param string $sql          SQL of query to execute
 * @param bool   $fatalOnError Abort execution if there is a database error?
 * @param bool   $showError    Display error to user (including possibly the
 *                             SQL) if there is a database error?
 *
 * @return mixed The query result resource on queries (which can then be
 *               passed to the {@link dbi_fetch_row()} function to obtain the
 *               results), or true/false on insert or delete queries.
 */
function dbi_query($sql, $fatalOnError = true, $showError = true)
{
    global $phpdbiVerbose;
    if (strcmp($GLOBALS["db_type"], "mysql") == 0) {
        $res = mysql_query($sql);
        if (!$res) {
            dbi_fatal_error("Error executing query." . $phpdbiVerbose ? dbi_error() . "\n\n<br />\n" . $sql : "" . "", $fatalOnError, $showError);
        }
        return $res;
    } else {
        if (strcmp($GLOBALS["db_type"], "mysqli") == 0) {
            $res = mysqli_query($GLOBALS["db_connection"], $sql);
            if (!$res) {
                dbi_fatal_error("Error executing query." . $phpdbiVerbose ? dbi_error() . "\n\n<br />\n" . $sql : "" . "", $fatalOnError, $showError);
            }
            return $res;
        } else {
            if (strcmp($GLOBALS["db_type"], "mssql") == 0) {
                $res = mssql_query($sql);
                if (!$res) {
                    dbi_fatal_error("Error executing query." . $phpdbiVerbose ? dbi_error() . "\n\n<br />\n" . $sql : "" . "", $fatalOnError, $showError);
                }
                return $res;
            } else {
                if (strcmp($GLOBALS["db_type"], "oracle") == 0) {
                    $GLOBALS["oracle_statement"] = OCIParse($GLOBALS["oracle_connection"], $sql);
                    return OCIExecute($GLOBALS["oracle_statement"], OCI_COMMIT_ON_SUCCESS);
                } else {
                    if (strcmp($GLOBALS["db_type"], "postgresql") == 0) {
                        @($GLOBALS["postgresql_row[\"{$res}\"]"] = 0);
                        $res = pg_exec($GLOBALS["postgresql_connection"], $sql);
                        if (!$res) {
                            dbi_fatal_error("Error executing query." . $phpdbiVerbose ? dbi_error() . "\n\n<br />\n" . $sql : "" . "", $fatalOnError, $showError);
                        }
                        $GLOBALS["postgresql_numrows[\"{$res}\"]"] = pg_numrows($res);
                        return $res;
                    } else {
                        if (strcmp($GLOBALS["db_type"], "odbc") == 0) {
                            return odbc_exec($GLOBALS["odbc_connection"], $sql);
                        } else {
                            if (strcmp($GLOBALS["db_type"], "ibm_db2") == 0) {
                                $res = db2_exec($GLOBALS["ibm_db2_connection"], $sql);
                                if (!$res) {
                                    dbi_fatal_error("Error executing query." . $phpdbiVerbose ? dbi_error() . "\n\n<br />\n" . $sql : "" . "", $fatalOnError, $showError);
                                }
                                return $res;
                            } else {
                                if (strcmp($GLOBALS["db_type"], "ibase") == 0) {
                                    $res = ibase_query($sql);
                                    if (!$res) {
                                        dbi_fatal_error("Error executing query." . $phpdbiVerbose ? dbi_error() . "\n\n<br />\n" . $sql : "" . "", $fatalOnError, $showError);
                                    }
                                    return $res;
                                } else {
                                    dbi_fatal_error("dbi_query(): db_type not defined.");
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
 /**
  *	This function will connect to the database, execute a query and will return the result handle.
  *
  *	@param $sql	The SQL statement to execute.
  *
  *  @returns    Handle to the result of the query. In case of an error, this function triggers an error.
  *
  *	@internal
  */
 function &_connectAndExec($sql)
 {
     // Add the table prefix
     $sql = str_replace(' #_', ' ' . YDConfig::get('YD_DB_TABLEPREFIX', ''), $sql);
     // Update the language placeholders
     $languageIndex = YDConfig::get('YD_DB_LANGUAGE_INDEX', null);
     if (!is_null($languageIndex)) {
         $sql = str_replace('_@', '_' . $languageIndex, $sql);
     }
     // Connect
     $result = $this->connect();
     // Handle errors
     if (!$result && $this->_failOnError === true) {
         $error = ocierror();
         trigger_error($error['message'], YD_ERROR);
     }
     // Record the start time
     $timer = new YDTimer();
     // Create statement
     $stmt = OCIParse($this->_conn, $sql);
     // Handle errors
     if (!$stmt && $this->_failOnError === true) {
         $error = ocierror($stmt);
         trigger_error($error['message'], YD_ERROR);
     }
     // Execute
     $result = @OCIExecute($stmt);
     // Handle errors
     if ($result === false && $this->_failOnError === true) {
         $error = ocierror($stmt);
         if (!empty($error['sqltext'])) {
             $error['message'] .= ' (SQL: ' . $error['sqltext'] . ')';
         }
         echo '<b>Stacktrace:</b> <pre>' . YDDebugUtil::getStackTrace() . '</pre>';
         echo '<b>SQL Statement:</b> <pre>' . $this->formatSql($sql) . '</pre>';
         trigger_error($error['message'], YD_ERROR);
     }
     // Log the statement
     $this->_logSql($sql, $timer->getElapsed());
     // Return the result
     return $stmt;
 }
Example #16
0
            $e = oci_error($parsed);
            echo htmlentities($e['message']);
            exit;
        }
    } else {
        echo "<br>input invalid value.<br>";
    }
    // Select data...
    $cmdstr = "select * from tab1";
    $parsed = OCIParse($db_conn, $cmdstr);
    if (!$parsed) {
        $e = OCIError($db_conn);
        echo htmlentities($e['message']);
        exit;
    }
    $r = OCIExecute($parsed, OCI_DEFAULT);
    if (!$r) {
        $e = oci_error($parsed);
        echo htmlentities($e['message']);
        exit;
    }
    echo "<br>Got data from table tab1:<br>";
    while ($row = OCI_Fetch_Array($parsed, OCI_BOTH)) {
        echo $row["COL1"];
        echo "\n";
        echo $row["COL2"];
        echo "<br>";
    }
    OCICommit($db_conn);
    OCILogoff($db_conn);
} else {
Example #17
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 = '';
             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);
     }
 }
 /**
  *	This function will connect to the database, execute a query and will return the result handle.
  *
  *	@param $sql	The SQL statement to execute.
  *
  *	@returns	Handle to the result of the query.
  *
  *	@internal
  */
 function _connectAndExec($sql)
 {
     $this->_logSql($sql);
     $this->connect();
     $stmt = OCIParse($this->_conn, $sql);
     if (!$stmt) {
         $error = ocierror($stmt);
         trigger_error($error['message'], YD_ERROR);
     }
     $result = @OCIExecute($stmt);
     if (!$result) {
         $error = ocierror($stmt);
         if (!empty($error['sqltext'])) {
             $error['message'] .= ' (SQL: ' . $error['sqltext'] . ')';
         }
         trigger_error($error['message'], YD_ERROR);
     }
     return $stmt;
 }
 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;
 }
 function GetLastInsertID($sTable)
 {
     if (!($res = OCIParse($this->conn, "select currval(seq_{$sTable})"))) {
         trigger_error("Error parsing insert ID query!");
         return $this->ReportError($this->conn);
     }
     if (OCIExecute($res)) {
         @OCIFetchInto($res, $Record, OCI_NUM | OCI_ASSOC | OCI_RETURN_NULLS);
         @OCIFreeStatement($res);
         return $Record[0];
     }
     trigger_error("Error executing insert ID query!");
     return $this->ReportError($res);
 }
Example #21
0
 /**
  * Returns information about a table or a result set
  *
  * NOTE: only supports 'table' and 'flags' if <var>$result</var>
  * is a table name.
  *
  * NOTE: flags won't contain index information.
  *
  * @param object|string  $result  DB_result object from a query or a
  *                                 string containing the name of a table.
  *                                 While this also accepts a query result
  *                                 resource identifier, this behavior is
  *                                 deprecated.
  * @param int            $mode    a valid tableInfo mode
  *
  * @return array  an associative array with the information requested.
  *                 A DB_Error object on failure.
  *
  * @see DB_common::tableInfo()
  */
 function tableInfo($result, $mode = null)
 {
     if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
         $case_func = 'strtolower';
     } else {
         $case_func = 'strval';
     }
     $res = array();
     if (is_string($result)) {
         /*
          * Probably received a table name.
          * Create a result resource identifier.
          */
         $result = strtoupper($result);
         $q_fields = 'SELECT column_name, data_type, data_length, ' . 'nullable ' . 'FROM user_tab_columns ' . "WHERE table_name='{$result}' ORDER BY column_id";
         $this->last_query = $q_fields;
         if (!($stmt = @OCIParse($this->connection, $q_fields))) {
             return $this->oci8RaiseError(DB_ERROR_NEED_MORE_DATA);
         }
         if (!@OCIExecute($stmt, OCI_DEFAULT)) {
             return $this->oci8RaiseError($stmt);
         }
         $i = 0;
         while (@OCIFetch($stmt)) {
             $res[$i] = array('table' => $case_func($result), 'name' => $case_func(@OCIResult($stmt, 1)), 'type' => @OCIResult($stmt, 2), 'len' => @OCIResult($stmt, 3), 'flags' => @OCIResult($stmt, 4) == 'N' ? 'not_null' : '');
             if ($mode & DB_TABLEINFO_ORDER) {
                 $res['order'][$res[$i]['name']] = $i;
             }
             if ($mode & DB_TABLEINFO_ORDERTABLE) {
                 $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
             }
             $i++;
         }
         if ($mode) {
             $res['num_fields'] = $i;
         }
         @OCIFreeStatement($stmt);
     } else {
         if (isset($result->result)) {
             /*
              * Probably received a result object.
              * Extract the result resource identifier.
              */
             $result = $result->result;
         }
         $res = array();
         if ($result === $this->last_stmt) {
             $count = @OCINumCols($result);
             if ($mode) {
                 $res['num_fields'] = $count;
             }
             for ($i = 0; $i < $count; $i++) {
                 $res[$i] = array('table' => '', 'name' => $case_func(@OCIColumnName($result, $i + 1)), 'type' => @OCIColumnType($result, $i + 1), 'len' => @OCIColumnSize($result, $i + 1), 'flags' => '');
                 if ($mode & DB_TABLEINFO_ORDER) {
                     $res['order'][$res[$i]['name']] = $i;
                 }
                 if ($mode & DB_TABLEINFO_ORDERTABLE) {
                     $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
                 }
             }
         } else {
             return $this->raiseError(DB_ERROR_NOT_CAPABLE);
         }
     }
     return $res;
 }
Example #22
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;
     }
     //echo "Ejemplo: ".$cadena_sql."<br>";
     $cadenaParser = OCIParse($this->enlace, $cadena_sql);
     $busqueda = OCIExecute($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];
             //echo $this->registro[$j][$un_campo];
         }
         $this->conteo = $j--;
         //echo $this->conteo;
         @OCIFreeCursor($cadenaParser);
         return $this->conteo;
     } else {
         unset($this->registro);
         $this->error = oci_error();
         //echo $this->error();
         return 0;
     }
 }
Example #23
0
function DBexecute($query, $skip_error_messages = 0)
{
    global $DB;
    //COpt::savesqlrequest($query);
    $result = false;
    if (isset($DB['DB']) && !empty($DB['DB'])) {
        $DB['EXECUTE_COUNT']++;
        // WRONG FOR ORACLE!!
        //SDI('SQL Exec: '.$query);
        switch ($DB['TYPE']) {
            case 'MYSQL':
                $result = mysql_query($query, $DB['DB']);
                if (!$result) {
                    error('Error in query [' . $query . '] [' . mysql_error() . ']');
                }
                break;
            case 'POSTGRESQL':
                if (!($result = pg_query($DB['DB'], $query))) {
                    error('Error in query [' . $query . '] [' . pg_last_error() . ']');
                }
                break;
            case 'ORACLE':
                $stid = OCIParse($DB['DB'], $query);
                if (!$stid) {
                    $e = @ocierror();
                    error('SQL error [' . $e['message'] . '] in [' . $e['sqltext'] . ']');
                }
                $result = @OCIExecute($stid, $DB['TRANSACTIONS'] ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS);
                if (!$result) {
                    $e = ocierror($stid);
                    error('SQL error [' . $e['message'] . '] in [' . $e['sqltext'] . ']');
                } else {
                    $result = $stid;
                }
                break;
            case 'SQLITE3':
                if (!$DB['TRANSACTIONS']) {
                    lock_db_access();
                }
                $result = sqlite3_exec($DB['DB'], $query);
                if (!$result) {
                    error('Error in query [' . $query . '] [' . sqlite3_error($DB['DB']) . ']');
                }
                if (!$DB['TRANSACTIONS']) {
                    unlock_db_access();
                }
                break;
        }
        if ($DB['TRANSACTIONS'] && !$result) {
            $DB['TRANSACTION_STATE'] &= $result;
            //			SDI($query);
            //			SDI($DB['TRANSACTION_STATE']);
        }
    }
    return $result;
}
Example #24
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;
 }
Example #25
0
<?php

//putenv("NLS_LANG=RUSSIAN_CIS.CL8MSWIN1251");
$conn = oci_connect($oracle_db_user, $oracle_db_psw, "(DESCRIPTION =\n                      (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)\n                      (HOST = {$oracle_host})(PORT = {$oracle_port})))\n                      (CONNECT_DATA = (SID = {$oracle_sid})))", "UTF8");
if (!$conn) {
    $e = oci_error();
    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = OCIParse($conn, "ALTER SESSION SET NLS_DATE_FORMAT='DD.MM.YYYY'");
OCIExecute($sql, OCI_DEFAULT);
//$sql  = OCIParse($conn, "begin DBMS_APPLICATION_INFO.SET_ACTION(action_name => 'RP".substr(getcwd(),33).'|'.$_POST['user_name']."'); end;");
//OCIExecute($sql, OCI_DEFAULT);
//$sql  = OCIParse($conn, "begin ins.safety.set_rls_status(0); end;");
//OCIExecute($sql, OCI_DEFAULT);
if (!function_exists("db_query")) {
    function db_query($ASql, $AQueryType = 0)
    {
        global $conn;
        $ASql = "/*" . $_SERVER['REMOTE_ADDR'] . ", " . $_SERVER['SCRIPT_FILENAME'] . ", " . date('d.m.Y H:i', time()) . "*/" . $ASql;
        $result = oci_parse($conn, $ASql);
        $return = array();
        ociexecute($result, OCI_DEFAULT);
        switch ($AQueryType) {
            case 0:
                $return = oci_fetch_array($result, OCI_ASSOC);
                break;
            case 1:
                while ($row = oci_fetch_array($result, OCI_ASSOC)) {
                    $return[] = $row;
                }
                break;
	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;
	}
Example #27
0
 static function banderaOracle2($username, $db_conn)
 {
     $actualiza = "update pedro.usuario\r\nset \r\nsesion =null,\r\nsesion1=1\r\nWHERE \r\nLOGIN='******' ";
     $actualiza2 = OCIParse($db_conn, $actualiza);
     OCIExecute($actualiza2, OCI_DEFAULT);
     OCICommit($db_conn);
 }
Example #28
0
  <body>
<form name="form1" method="POST">  
<?php 
include "mod/nav.php";
include "config/connect.php";
$alert = "";
$sql = OCIParse($connect, "SELECT NO_TICARES, OLO, PRODUCT, CONCAT(KAPS, SAT) AS BW, RUAS, WITEL, REVENUE, KOMENTAR FROM SB_OLO WHERE NO_TICARES = '" . $_GET['id'] . "'");
ociexecute($sql);
$row = oci_fetch_array($sql);
if (isset($_POST['submit'])) {
    if (!empty($_POST['est_close'])) {
        $qtgl = " EST_CLOSE = TO_DATE('" . $_POST['est_close'] . "','DD/MM/YYYY'), ";
    } else {
        $qtgl = "";
    }
    OCIExecute(OCIParse($connect, "UPDATE SB_OLO SET\n                                STAT_SERVICE = '" . $_POST['progress'] . "',\n                                " . $qtgl . "REVENUE = '" . $_POST['revenue'] . "',\n                                KOMENTAR = '" . $_POST['comment'] . "',\n                                LAST_UPDATER = '" . $_SESSION['username'] . "'\n                                WHERE NO_TICARES = '" . $_GET['id'] . "'"));
    sql_ora("commit");
    $alert = "<div class=\"col-md-12\"><div class=\"form-group\"><div class=\"alert alert-dismissable alert-success\">\n          <button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button>\n          <strong>Done!</strong> Data berhasil diupdate!\n          </div></div></div>";
}
?>
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="panel panel-danger">
<div class="panel-heading">
    <h3 class="panel-title"><strong>FORM UPDATE OGP OLO</strong></h3>
</div>
<div class="panel-body">

<div class="row">
Example #29
0
if (!$iserror) {
    $dbuser = "******";
    $dbpass = "******";
    $db = "SSID";
    $connect = OCILogon($dbuser, $dbpass, $db);
    if (!$connect) {
        echo "<br />There was an error connecting to the database.";
        exit;
    }
    $query = "select * from book_table where unit_code = '{$unit_code}'";
    $stmt = OCIParse($connect, $query);
    if (!$stmt) {
        echo "An error occured in parsing the sql string.\n";
        exit;
    }
    OCIExecute($stmt);
    ?>
				<table>
					
					<?php 
    while (OCIFetch($stmt)) {
        echo "<tr>";
        echo "<td>IBSN</td>";
        $fg1 = OCIResult($stmt, "IBSN");
        echo "<td>";
        echo $fg1;
        echo "</td>";
        echo "</tr>";
        echo "<tr>";
        echo "<td>Title</td>";
        $fg2 = OCIResult($stmt, "TITLE");
Example #30
0
      oci_define_by_name($stmt, "KEYWORD", $keyword);
      oci_define_by_name($stmt, "TYPE", $type);
      oci_define_by_name($stmt, "KILL_ID", $id);
      oci_execute($stmt);
    while(oci_fetch($stmt)){*/
 $perNumber = 8;
 $page = 1;
 if (isset($_GET['page'])) {
     $page = $_GET['page'];
 }
 //$page = $_GET['page'];
 if ($page == false) {
     $page = 1;
 }
 $sql_exc_page = OCIParse($conn, "select * from KILL_KEY where TYPE='{$type}' order by KILL_ID desc");
 OCIExecute($sql_exc_page);
 $toltalnum = oci_fetch_all($sql_exc_page, $result);
 $totalpage = ceil($toltalnum / $perNumber);
 $sql_fenye = "select * from KILL_KEY where TYPE='{$type}' order by KILL_ID desc";
 $sql_exc_fenye = oci_parse($conn, $sql_fenye);
 oci_execute($sql_exc_fenye);
 $mID = 0;
 for ($i = 0; $i <= $perNumber * ($page - 1); $i++) {
     if (($row = oci_fetch_assoc($sql_exc_fenye)) != false) {
         $mID = $row['KILL_ID'];
     } else {
         print "<script>alert('无记录')</script>";
     }
 }
 $sql_fenye = "select * from KILL_KEY where TYPE='{$type}' and KILL_ID <= {$mID}  order by KILL_ID desc";
 $sql_exc = oci_parse($conn, $sql_fenye);