public function export() { // Método encargado de exportar el query a excel.. global $conn; $result = $this->header; $result.= "<table border=1>"; $stmt = DBExecSql($conn, $this->sql); if (DBGetRecordCount($stmt) > 0) { $cols = 0; while($row = DBGetQuery($stmt, 0)) { // Exporto el nombre de las columnas.. if ($cols == 0) { $cols = count($row); if ($this->showFieldNames) { $result.= "<tr>"; for ($i=1; $i<=$cols; $i++) { $col_name = OCIColumnName($stmt, $i); if (substr($col_name, 0, 3) != "NO_") { $alineacion = "left"; if (isset($this->fieldAlignment[$i - 1])) $alineacion = $this->fieldAlignment[$i - 1]; $result.= "<th align=".$alineacion." style='".$this->fieldNamesStyle."'>".$col_name."</th>"; } } $result.= "</tr>"; } } // Exporto el valor de los campos.. $result.= "<tr>"; for ($i=0; $i<$cols; $i++) { $col_name = OCIColumnName($stmt, $i + 1); if (substr($col_name, 0, 3) != "NO_") { $alineacion = "left"; if (isset($this->fieldAlignment[$i])) $alineacion = $this->fieldAlignment[$i]; $result.= "<td align=".$alineacion." style='".$this->fieldValuesStyle."'>".$row[$i]."</td>"; } } $result.= "</tr>"; } } else $result.= "<tr><td>No hay registros para exportar.</td></tr>"; $result.= "</table>"; header("Content-type: ".$this->getHeader()."; charset=iso-8859-1"); header("Content-Disposition: attachment; filename=".basename($this->fileName.$this->getExtension())); header("Pragma: no-cache"); header("Content-Length: ".strlen($result)); header("Expires: 0"); echo $result; }
/** * Retrieve the names of columns returned by the DBMS in a query result. * * @return mixed Array variable that holds the names of columns as keys * or an MDB2 error on failure. * Some DBMS may not return any columns when the result set * does not contain any rows. * @access private */ function _getColumnNames() { $columns = array(); $numcols = $this->numCols(); if (PEAR::isError($numcols)) { return $numcols; } for ($column = 0; $column < $numcols; $column++) { $column_name = @OCIColumnName($this->result, $column + 1); $columns[$column_name] = $column; } if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { $columns = array_change_key_case($columns, $this->db->options['field_case']); } return $columns; }
/** * 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 MDB2_result object from a query or a * string containing the name of a table * @param int $mode a valid tableInfo mode * @return array an associative array with the information requested * or an error object if something is wrong * @access public * @internal * @see MDB2_Driver_Common::tableInfo() */ function tableInfo($result, $mode = null) { $db =& $GLOBALS['_MDB2_databases'][$this->db_index]; if ($db->options['portability'] & MDB2_PORTABILITY_LOWERCASE) { $case_func = 'strtolower'; } else { $case_func = 'strval'; } if (is_string($result)) { /* * Probably received a table name. * Create a result resource identifier. */ if (MDB2::isError($connect = $db->connect())) { return $connect; } $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"; $db->last_query = $q_fields; if (!($stmt = @OCIParse($db->connection, $q_fields))) { return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA); } if (!@OCIExecute($stmt, OCI_DEFAULT)) { return $db->raiseError($stmt); } $i = 0; while (@OCIFetch($stmt)) { $res[$i]['table'] = $case_func($result); $res[$i]['name'] = $case_func(@OCIResult($stmt, 1)); $res[$i]['type'] = @OCIResult($stmt, 2); $res[$i]['len'] = @OCIResult($stmt, 3); $res[$i]['flags'] = @OCIResult($stmt, 4) == 'N' ? 'not_null' : ''; if ($mode & MDB2_TABLEINFO_ORDER) { $res['order'][$res[$i]['name']] = $i; } if ($mode & MDB2_TABLEINFO_ORDERTABLE) { $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; } $i++; } if ($mode) { $res['num_fields'] = $i; } @OCIFreeStatement($stmt); } else { /* * Probably received a result object. * Extract the result resource identifier. */ $id = $result->getResource(); if (empty($id)) { return $db->raiseError(); } # if ($result === $db->last_stmt) { $count = @OCINumCols($id); for ($i = 0; $i < $count; $i++) { $res[$i]['table'] = ''; $res[$i]['name'] = $case_func(@OCIColumnName($id, $i + 1)); $res[$i]['type'] = @OCIColumnType($id, $i + 1); $res[$i]['len'] = @OCIColumnSize($id, $i + 1); $res[$i]['flags'] = ''; if ($mode & MDB2_TABLEINFO_ORDER) { $res['order'][$res[$i]['name']] = $i; } if ($mode & MDB2_TABLEINFO_ORDERTABLE) { $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; } } if ($mode) { $res['num_fields'] = $i; } # } else { # return $db->raiseError(MDB2_ERROR_NOT_CAPABLE); # } } return $res; }
/** * Get the name of the specified field in a result * @param Mixed qHanle The query handle * @param Number offset * @return String */ public function field_name($qHanle, $offset) { return OCIColumnName($qHanle, $offset + 1); }
/** * Retrieve the names of columns returned by the DBMS in a query result. * * @return mixed associative array variable * that holds the names of columns. The indexes of the array are * the column names mapped to lower case and the values are the * respective numbers of the columns starting from 0. Some DBMS may * not return any columns when the result set does not contain any * rows. * @access public */ function getColumnNames() { $columns = array(); $numcols = $this->numCols(); if (MDB2::isError($numcols)) { return $numcols; } for ($column = 0; $column < $numcols; $column++) { $column_name = @OCIColumnName($this->result, $column + 1); $columns[$column_name] = $column; } if ($this->mdb->options['portability'] & MDB2_PORTABILITY_LOWERCASE) { $columns = array_change_key_case($columns, CASE_LOWER); } return $columns; }
function sql_fieldname($offset, $query_id = 0) { // OCIColumnName uses a 1 based array so we have to up the offset by 1 in here to maintain // full abstraction compatibitly $offset += 1; if (!$query_id) { $query_id = $this->query_result; } if ($query_id) { $result = strtolower(@OCIColumnName($query_id, $offset)); return $result; } else { return false; } }
/** * 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; }
/** * 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 MDB2_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 MDB2_Error object on failure. * * @see MDB2_Driver_Common::tableInfo() */ function tableInfo($result, $mode = null) { if (is_string($result)) { return parent::tableInfo($result, $mode); } $db =& $this->getDBInstance(); if (PEAR::isError($db)) { return $db; } $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result; if (!is_resource($resource)) { return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, 'Could not generate result resource', __FUNCTION__); } if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) { if ($db->options['field_case'] == CASE_LOWER) { $case_func = 'strtolower'; } else { $case_func = 'strtoupper'; } } else { $case_func = 'strval'; } $count = @OCINumCols($resource); $res = array(); if ($mode) { $res['num_fields'] = $count; } $db->loadModule('Datatype', null, true); for ($i = 0; $i < $count; $i++) { $column = array('table' => '', 'name' => $case_func(@OCIColumnName($resource, $i + 1)), 'type' => @OCIColumnType($resource, $i + 1), 'length' => @OCIColumnSize($resource, $i + 1), 'flags' => ''); $res[$i] = $column; $res[$i]['mdb2type'] = $db->datatype->mapNativeDatatype($res[$i]); if ($mode & MDB2_TABLEINFO_ORDER) { $res['order'][$res[$i]['name']] = $i; } if ($mode & MDB2_TABLEINFO_ORDERTABLE) { $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; } } return $res; }
/** * Emulate the row limit support altering the query * * @param string $query The query to treat * @param int $from The row to start to fetch from * @param int $count The offset * @return string The modified query * * @author Tomas V.V.Cox <*****@*****.**> */ function modifyLimitQuery($query, $from, $count) { // Let Oracle return the name of the columns instead of // coding a "home" SQL parser $q_fields = "SELECT * FROM ({$query}) WHERE NULL = NULL"; if (!($result = OCIParse($this->connection, $q_fields))) { return $this->oci8RaiseError(); } if (!OCIExecute($result, OCI_DEFAULT)) { return $this->oci8RaiseError($result); } $ncols = OCINumCols($result); $cols = array(); for ($i = 1; $i <= $ncols; $i++) { $cols[] = OCIColumnName($result, $i); } $fields = implode(', ', $cols); // XXX Test that (tip by John Lim) //if(preg_match('/^\s*SELECT\s+/is', $query, $match)) { // // Introduce the FIRST_ROWS Oracle query optimizer // $query = substr($query, strlen($match[0]), strlen($query)); // $query = "SELECT /* +FIRST_ROWS */ " . $query; //} // Construct the query // more at: http://marc.theaimsgroup.com/?l=php-db&m=99831958101212&w=2 // Perhaps this could be optimized with the use of Unions $from += 1; // in Oracle rownum starts at 1 $query = "SELECT {$fields} FROM" . " (SELECT rownum as linenum, {$fields} FROM" . " ({$query})" . " WHERE rownum <= " . ($from + $count) . ") WHERE linenum >= {$from}"; return $query; }
function query($query) { // For reg expressions $query = trim($query); $return_value = 0; // Flush cached values.. $this->flush(); // Log how the function was called $this->func_call = "\$db->query(\"{$query}\")"; // Keep track of the last query for debug.. $this->last_query = $query; // Parses the query and returns a statement.. if (!($stmt = OCIParse($this->dbh, $query))) { $this->print_error("Last Query", $query); } elseif (!($this->result = OCIExecute($stmt))) { $this->print_error("Last Query", $query); } $this->num_queries++; // If query was an insert if (preg_match('/^(insert|delete|update|create)\\s+/i', $query)) { // num afected rows $return_value = $this->rows_affected = OCIRowCount($stmt); } else { // Get column information if ($num_cols = @OCINumCols($stmt)) { // Fetch the column meta data for ($i = 1; $i <= $num_cols; $i++) { $this->col_info[$i - 1]->name = OCIColumnName($stmt, $i); $this->col_info[$i - 1]->type = OCIColumnType($stmt, $i); $this->col_info[$i - 1]->size = OCIColumnSize($stmt, $i); } } // If there are any results then get them if ($this->num_rows = @OCIFetchStatement($stmt, $results)) { // Convert results into object orientated results.. // Due to Oracle strange return structure - loop through columns foreach ($results as $col_title => $col_contents) { $row_num = 0; // then - loop through rows foreach ($col_contents as $col_content) { $this->last_result[$row_num]->{$col_title} = $col_content; $row_num++; } } } // num result rows $return_value = $this->num_rows; } // If debug ALL queries $this->trace || $this->debug_all ? $this->debug() : null; return $return_value; }
function execute_request($value_query, $value_config, $Param) { global $debug; //Constitution de la requete finale $requete = $value_query['code_sql']; if (!is_array($Param)) { eko("pb d'argument pour requete {$requete}"); } while (list($key, $val) = each($Param)) { $searched_str = "\$" . $key; $requete = str_replace($searched_str, $val, $requete); } // echo $requete; // On place les colonnes à ramener dans un tableau $tab_cols if ($value_query['colonnes'] != '*' & $value_query['colonnes'] != '') { $tab_cols = split(",", $value_query['colonnes']); } switch ($value_config['type']) { case "MySQL": // Connexion au serveur Mysql & Execution de la requete // eko ( $value_config ) ; $conn = @mysql_connect($value_config['host'], $value_config['login'], $value_config['password']); if (!$conn) { global $errs; if ($errs) { $errs->addErreur("La connexion au serveur MySQL \"" . $value_config['host'] . "\" avec l'utilisateur \"" . $value_config['login'] . "\" et le mot de passe \"*******\" a échoué."); } } // eko ( "connexion : ".$value_config[login]."/".$value_config[password]."@". $value_config[host] ) ; $INDIC_SVC[0] = mysql_errno(); $INDIC_SVC[1] = mysql_error(); // pas de problème de connexion if (!$INDIC_SVC[0]) { // execution de la raquete if (!$this->forceBase) { $result = @mysql_select_db($value_config['db']); } else { $result = @mysql_select_db($this->forceBase); } $result = @mysql_query($requete); //echo "<h1>REQUETE : $requete</h1>"; $INDIC_SVC[0] = mysql_errno(); $INDIC_SVC[1] = mysql_error(); // pas de problème à l'execution de la requete if (!$INDIC_SVC[0]) { // Analyse du type de requete if (DEBUGSQL and function_exists('eko')) { eko($requete); } $qry_type = explode(" ", $requete); switch (strtoupper($qry_type[0])) { case "SELECT": $nrows = mysql_num_rows($result); if ($nrows) { // le nom des colonnes a ramener est * if (!isset($tab_cols)) { for ($i = 0; $i < mysql_num_fields($result); $i++) { $tab_cols[] = mysql_field_name($result, $i); } } // Maintenant On connait $tab_cols while ($record = mysql_fetch_array($result)) { // affectation dans les tableau de colonnes //jeton de debugage quand même colones unset($jeton); while (list($key, $val) = each($tab_cols)) { if (!isset($jeton[$val])) { $jeton[$val] = true; } else { $jeton[$val] = false; } if (isset(${$val})) { if ($jeton[$val]) { ${$val} .= $record[$val] . "§"; //if ($debug) eko($val."-".$$val); } } else { ${$val} = $record[$val] . "§"; } } reset($tab_cols); } //Construction des tableaux de colonnes unset($jeton); //print "********************* Tableau **********************<br>".affTab ( $tab_cols ) ; while (list($key, $val) = each($tab_cols)) { //print "/////////////////// Case ////////////////////<br>".affTab ( $jeton[$val] ) ; if (!isset($jeton[$val])) { $jeton[$val] = true; } else { $jeton[$val] = false; } if ($jeton[$val]) { // on retire le dernier | //print "<br>dollardollarval : ".$$val ; ${$val} = substr(${$val}, 0, strlen(${$val}) - 1); $resultats[$val] = explode("§", ${$val}); } //if ($debug) eko($resultats[$val]); } } $INDIC_SVC[2] = $nrows; break; case "INSERT": $INDIC_SVC[2] = mysql_affected_rows(); $INDIC_SVC[3] = mysql_insert_id(); break; case "UPDATE": case "DELETE": $INDIC_SVC[2] = mysql_affected_rows(); break; } } } //mysql_close ( $conn ) ; break; case "MSSQL": // Connexion au serveur Mssql & Execution de la requete //print affTab ( $value_config ) ; //mssql_connect('galileo.ch-brignoles.fr','user_dim' ,'') || die ( 'hop' ) ; //mssql_connect("galileo","user_dim","") ||die ("Connexion impossible au serveur!"); $conn = mssql_pconnect($value_config['host'], $value_config['login'], $value_config['password']); if (!$conn) { global $errs; if ($errs) { $errs->addErreur("La connexion au serveur MsSQL \"" . $value_config['host'] . "\" avec l'utilisateur \"" . $value_config['login'] . "\" et le mot de passe \"*******\" a échoué."); } } // eko ( "connexion : ".$value_config[login]."/".$value_config[password]."@". $value_config[host] ) ; //$INDIC_SVC[0] = mssql_get_last_message ( ) ; //$INDIC_SVC[1] = mssql_get_last_message ( ) ; // pas de problème de connexion if (!$INDIC_SVC[0]) { // execution de la raquete $result = mssql_select_db($value_config['db']); $result = mssql_query($requete); //echo "<h1>REQUETE : $requete</h1>"; //$INDIC_SVC[0] = mssql_get_last_message ( ) ; //$INDIC_SVC[1] = mssql_get_last_message ( ) ; // pas de problème à l'execution de la requete if (!$INDIC_SVC[0]) { // Analyse du type de requete if (DEBUGSQL and function_exists('eko')) { eko($requete); } $qry_type = explode(" ", $requete); switch (strtoupper($qry_type[0])) { case "SELECT": $nrows = mssql_num_rows($result); //eko ( "nombre de lignes : $nrows" ) ; if ($nrows) { // le nom des colonnes a ramener est * if (!isset($tab_cols)) { for ($i = 0; $i < mssql_num_fields($result); $i++) { $tab_cols[] = mssql_field_name($result, $i); } } // Maintenant On connait $tab_cols while ($record = mssql_fetch_array($result)) { // affectation dans les tableau de colonnes //jeton de debugage quand même colones unset($jeton); while (list($key, $val) = each($tab_cols)) { if (!isset($jeton[$val])) { $jeton[$val] = true; } else { $jeton[$val] = false; } if (isset(${$val})) { if ($jeton[$val]) { ${$val} .= $record[$val] . "§"; // eko ( $record[$val] ) ; //if ($debug) eko($val."-".$$val); } } else { ${$val} = $record[$val] . "§"; } } reset($tab_cols); } // Construction des tableaux de colonnes unset($jeton); while (list($key, $val) = each($tab_cols)) { if (!isset($jeton[$val])) { $jeton[$val] = true; } else { $jeton[$val] = false; } if ($jeton[$val]) { // on retire le dernier | //print "<br>dollardollarval : ".$$val ; ${$val} = substr(${$val}, 0, strlen(${$val}) - 1); $resultats[$val] = explode("§", ${$val}); } //if ($debug) eko($resultats[$val]); } } $INDIC_SVC[2] = $nrows; break; case "INSERT": //$INDIC_SVC[2] = mssql_affected_rows ( ) ; //$INDIC_SVC[3] = mssql_insert_id ( ) ; break; case "UPDATE": case "DELETE": //$INDIC_SVC[2] = mssql_affected_rows ( ) ; break; } } } mssql_close($conn); break; case "ORACLE": //echo "oracle"; // Connexion // eko ($value_config); // $conn = @OCILogon ( $value_config['login'], $value_config['password'], $value_config['db'] ) ; $conn = @oci_pconnect($value_config['login'], $value_config['password'], $value_config['db']); //global $conn ; $conn_error = ocierror(); // Problème à la connexion if ($conn_error) { $INDIC_SVC[0] = $conn_error['code']; $INDIC_SVC[1] = $conn_error['message']; // pas de problème de connexion } else { // print $requete; // execution de la raquete $stmt = OCIParse($conn, $requete); // print ( $requete ) ; if (DEBUGSQL and function_exists('eko')) { eko($requete); } OCIExecute($stmt); $INDIC_SVC[0] = $conn_error['code']; $INDIC_SVC[1] = $conn_error['message']; // pas de problème à l'execution de la requete if (!$INDIC_SVC[0]) { // Analyse du type de requete $qry_type = OCIStatementType($stmt); switch ($qry_type) { case "SELECT": $nrows = OCIFetchStatement($stmt, $results); // eko ( "<P>There are $nrows records containing your criteria. ($requete)</P>" ) ; if ($nrows) { // le nom des colonnes a ramener n'a pas été spécifié ou est * if (!isset($tab_cols)) { $ncols = OCINumCols($stmt); for ($k = 1; $k <= $ncols; $k++) { $tab_cols[] = OCIColumnName($stmt, $k); } } for ($j = 0; $j < $nrows; $j++) { if (isset($tab_cols) and is_array($tab_cols)) { while (list($key, $val) = each($tab_cols)) { if (isset(${$val})) { ${$val} .= $results[$val][$j] . "§"; } else { ${$val} = $results[$val][$j] . "§"; } } } reset($tab_cols); } } //Construction des tableaux de colonnes if (isset($tab_cols) and is_array($tab_cols)) { while (list($key, $val) = each($tab_cols)) { // on retire le dernier | ${$val} = substr(${$val}, 0, strlen(${$val}) - 1); $resultats[$val] = explode("§", ${$val}); } } $INDIC_SVC[2] = $nrows; break; case "INSERT": $nrows = OCIRowCount($stmt); $INDIC_SVC[2] = $nrows; break; case "UPDATE": case "DELETE": $nrows = OCIRowCount($stmt); $INDIC_SVC[2] = $nrows; break; } } } oci_close($conn); break; case "LDAP": // Connexion au serveur LDAP $ds = @ldap_connect($value_config['host']); $bind = @ldap_bind($ds); if ($ds) { // On eclate les instructions LDAP dans un tableau $instructions_ldap = explode("##", $requete); $chemin = $instructions_ldap[0]; $filtre = $instructions_ldap[1]; // Fin de gestion du code sql // Execution de la requete $sr = ldap_search($ds, $chemin, $filtre); // le nom des colonnes a ramener n'a pas été spécifié ou est * if (!isset($tab_cols)) { $entry = ldap_first_entry($ds, $sr); $attrs = ldap_get_attributes($ds, $entry); for ($l = 0; $l < sizeof($attrs); $l++) { $tab_cols[] = $attrs[$l]; } } $result = ldap_get_entries($ds, $sr); for ($i = 0; $i < $result["count"]; $i++) { // test des attributs multivalués while (list($key, $val) = each($tab_cols)) { for ($v = 0; $v < sizeof($result[$i][$val]); $v++) { if ($result[$i][$val][$v] != "") { if ($v == 0) { $separateur = ""; } else { $separateur = "##"; } $valeur_brut = explode(",", $result[$i][$val][$v]); if ($valeur_brut[1]) { $valeur_pure = explode("cn=", $valeur_brut[0]); } else { $valeur_pure[1] = $result[$i][$val][$v]; } ${$val} .= $separateur . $valeur_pure[1]; } } ${$val} .= ","; } reset($tab_cols); } // Construction des tableaux de colonnes while (list($key, $val) = each($tab_cols)) { // on retire la dernière virgule ${$val} = substr(${$val}, 0, strlen(${$val}) - 1); $resultats[$val] = explode(",", ${$val}); } } $INDIC_SVC[0] = ldap_errno($ds); $INDIC_SVC[1] = ldap_error($ds); $INDIC_SVC[2] = $result["count"]; break; } $INDIC_SVC[15] = $requete; if (isset($Param['RIFIFI'])) { echo "indicsvc[0]:{$INDIC_SVC['0']}<br>indicsvc[1]:{$INDIC_SVC['1']}<br>indicsvc[2]:{$INDIC_SVC['2']}<br>indicsvc[3]:{$INDIC_SVC['3']}<br>indicsvc[15]:{$INDIC_SVC['15']}<br>\n"; } $resultats['INDIC_SVC'] = $INDIC_SVC; return $resultats; }
function query($query) { //去掉查询语句的前后空格 $query = trim($query); $return_value = 0; //清空缓存.. $this->flush(); //记录此函数如何被调用,用于调试... $this->func_call = "\$db->query(\"{$query}\")"; //跟踪最后查询语句,用于调试.. $this->last_query = $query; //解析查询语句 if (!($stmt = OCIParse($this->dbh, $query))) { $this->print_error(); } elseif (!($this->result = OCIExecute($stmt))) { $this->print_error(); } $this->num_queries++; //执行insert, delete, update, replace操作 if (preg_match('/^(insert|delete|update|create)\\s+/i', $query)) { //获取操作所影响的记录行数 $return_value = $this->rows_affected = OCIRowCount($stmt); } else { //获取字段信息 if ($num_cols = @OCINumCols($stmt)) { for ($i = 1; $i <= $num_cols; $i++) { $this->col_info[$i - 1]->name = OCIColumnName($stmt, $i); $this->col_info[$i - 1]->type = OCIColumnType($stmt, $i); $this->col_info[$i - 1]->size = OCIColumnSize($stmt, $i); } } //获取查询结果 if ($this->num_rows = @OCIFetchStatement($stmt, $results)) { //将结果集转变成对象,因为oracle的返回结果比较奇怪:) foreach ($results as $col_title => $col_contents) { $row_num = 0; //循环所有的行 foreach ($col_contents as $col_content) { $this->last_result[$row_num]->{$col_title} = $col_content; $row_num++; } } } //获取查询结果行数 $return_value = $this->num_rows; } //是否显示所有的查询信息 $this->debug_all ? $this->debug() : null; return $return_value; }
function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $arg3 = false, $secs2cache = 0) { $sql = preg_replace('/^[ \\t]*select/i', 'SELECT /*+FIRST_ROWS*/', $sql); if ($offset < 100) { if ($nrows > 0) { if ($offset > 0) { $nrows += $offset; } //$inputarr['adodb_rownum'] = $nrows; $sql = "select * from ({$sql}) where rownum <= {$nrows}"; $nrows = -1; } // note that $nrows = 0 still has to work ==> no rows returned return ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $arg3, $secs2cache); } else { // Algorithm by Tomas V V Cox, from PEAR DB oci8.php // Let Oracle return the name of the columns $q_fields = "SELECT * FROM ({$sql}) WHERE NULL = NULL"; if (!($result = OCIParse($this->_connectionID, $q_fields))) { return false; } if (!($success = OCIExecute($result, OCI_DEFAULT))) { return false; } $ncols = OCINumCols($result); for ($i = 1; $i <= $ncols; $i++) { $cols[] = OCIColumnName($result, $i); } $result = false; $fields = implode(',', $cols); $nrows += $offset; $offset += 1; // in Oracle rownum starts at 1 $sql = "SELECT {$fields} FROM" . "(SELECT rownum as adodb_rownum, {$fields} FROM" . " ({$sql}) WHERE rownum <= {$nrows}" . ") WHERE adodb_rownum >= {$offset}"; if ($secs2cache > 0) { return $this->CacheExecute($secs2cache, $sql, $inputarr, $arg3); } else { return $this->Execute($sql, $inputarr, $arg3); } } }
function FieldName($iCol) { return OCIColumnName($this->result, $iCol + 1); }
function &SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs2cache = 0) { // seems that oracle only supports 1 hint comment in 8i if ($this->firstrows) { if (strpos($sql, '/*+') !== false) { $sql = str_replace('/*+ ', '/*+FIRST_ROWS ', $sql); } else { $sql = preg_replace('/^[ \\t\\n]*select/i', 'SELECT /*+FIRST_ROWS*/', $sql); } } if ($offset < $this->selectOffsetAlg1 && 0 < $nrows && $nrows < 1000) { if ($nrows > 0) { if ($offset > 0) { $nrows += $offset; } //$inputarr['adodb_rownum'] = $nrows; if ($this->databaseType == 'oci8po') { $sql = "select * from (" . $sql . ") where rownum <= ?"; } else { $sql = "select * from (" . $sql . ") where rownum <= :adodb_offset"; } $inputarr['adodb_offset'] = $nrows; $nrows = -1; } // note that $nrows = 0 still has to work ==> no rows returned $rs =& ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); return $rs; } else { // Algorithm by Tomas V V Cox, from PEAR DB oci8.php // Let Oracle return the name of the columns $q_fields = "SELECT * FROM (" . $sql . ") WHERE NULL = NULL"; $false = false; if (!($stmt_arr = $this->Prepare($q_fields))) { return $false; } $stmt = $stmt_arr[1]; if (is_array($inputarr)) { // If there are any numeric keys, all key must be in an integer sequence // starting at 0 without any gaps for OCIBindByName() to work. $arr4fields = $inputarr; foreach ($inputarr as $k => $v) { if (is_int($k)) { // Reindex array $arr4fields = array_values($inputarr); break; } } foreach ($arr4fields as $k => $v) { if (is_array($v)) { if (sizeof($v) == 2) { // suggested by g.giunta@libero. OCIBindByName($stmt, ":{$k}", $arr4fields[$k][0], $v[1]); } else { OCIBindByName($stmt, ":{$k}", $arr4fields[$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}", $arr4fields[$k], $len); } } } } if (!OCIExecute($stmt, OCI_DEFAULT)) { OCIFreeStatement($stmt); return $false; } $ncols = OCINumCols($stmt); for ($i = 1; $i <= $ncols; $i++) { $cols[] = '"' . OCIColumnName($stmt, $i) . '"'; } $result = false; OCIFreeStatement($stmt); $fields = implode(',', $cols); $nrows_placeholder = $offset_placeholder = '?'; if ($this->databaseType != 'oci8po') { $nrows_placeholder = ':adodb_nrows'; $offset_placeholder = ':adodb_offset'; } if ($offset >= 0 && $nrows >= 0) { $sql = "SELECT {$fields} FROM" . "(SELECT rownum as adodb_rownum, {$fields} FROM" . " ({$sql}) WHERE rownum <= {$nrows_placeholder}" . ") WHERE adodb_rownum >= {$offset_placeholder}"; $offset += 1; // in Oracle rownum starts at 1 $nrows += $offset; $inputarr['adodb_nrows'] = $nrows; $inputarr['adodb_offset'] = $offset; } else { if ($offset >= 0) { $sql = "SELECT {$fields} FROM" . "(SELECT rownum as adodb_rownum, {$fields} FROM" . " ({$sql})" . ") WHERE adodb_rownum >= {$offset_placeholder}"; $offset += 1; // in Oracle rownum starts at 1 $inputarr['adodb_offset'] = $offset; } else { if ($nrows >= 0) { $sql = "SELECT {$fields} FROM" . " ({$sql}) WHERE rownum <= {$nrows_placeholder}"; $inputarr['adodb_nrows'] = $nrows; } } } // else $sql is unchanged if ($secs2cache > 0) { $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr); } else { $rs =& $this->Execute($sql, $inputarr); } return $rs; } }
function GetColumnNames($result, &$column_names) { $result_value = intval($result); if (!isset($this->highest_fetched_row[$result_value])) { return $this->SetError("Get column names", "it was specified an inexisting result set"); } if (!isset($this->columns[$result_value])) { $this->columns[$result_value] = array(); $columns = OCINumCols($result); for ($column = 0; $column < $columns; $column++) { $this->columns[$result_value][strtolower(OCIColumnName($result, $column + 1))] = $column; } } $column_names = $this->columns[$result_value]; return 1; }
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; }
function da_sql_list_fields($table, $link, $config) { $res = @da_sql_query($link, $config, "SELECT * from {$table} WHERE ROWNUM <=1"); if ($res) { $fields[res] = array(); for ($i = 1; $i <= ocinumcols($res); $i++) { array_push($fields[res], strtolower(OCIColumnName($res, $i))); } $fields[num] = @ocinumcols($res); } else { return NULL; } return $fields; }
function GetFieldName($fieldIndex) { if ($this->res) { return strtolower(OCIColumnName($this->res, $fieldIndex)); } return ''; }
function query($query) { $return_value = 0; // Flush cached values.. $this->flush(); // Log how the function was called $this->func_call = "\$db->query(\"{$query}\")"; // Keep track of the last query for debug.. $this->last_query = $query; $this->count(true, true); // Use core file cache function if ($cache = $this->get_cache($query)) { return $cache; } // If there is no existing database connection then try to connect if (!isset($this->dbh) || !$this->dbh) { $this->connect($this->dbuser, $this->dbpassword, $this->dbname); } // Parses the query and returns a statement.. if (!($stmt = OCIParse($this->dbh, $query))) { $error = OCIError($this->dbh); $this->register_error($error["message"]); $this->show_errors ? trigger_error($error["message"], E_USER_WARNING) : null; return false; } elseif (!($this->result = OCIExecute($stmt))) { $error = OCIError($stmt); $this->register_error($error["message"]); $this->show_errors ? trigger_error($error["message"], E_USER_WARNING) : null; return false; } // If query was an insert $is_insert = false; if (preg_match('/^(insert|delete|update|create) /i', $query)) { $is_insert = true; // num afected rows $return_value = $this->rows_affected = @OCIRowCount($stmt); } else { // Get column information if ($num_cols = @OCINumCols($stmt)) { // Fetch the column meta data for ($i = 1; $i <= $num_cols; $i++) { $this->col_info[$i - 1]->name = @OCIColumnName($stmt, $i); $this->col_info[$i - 1]->type = @OCIColumnType($stmt, $i); $this->col_info[$i - 1]->size = @OCIColumnSize($stmt, $i); } } // If there are any results then get them if ($this->num_rows = @OCIFetchStatement($stmt, $results)) { // Convert results into object orientated results.. // Due to Oracle strange return structure - loop through columns foreach ($results as $col_title => $col_contents) { $row_num = 0; // then - loop through rows foreach ($col_contents as $col_content) { $this->last_result[$row_num]->{$col_title} = $col_content; $row_num++; } } } // num result rows $return_value = $this->num_rows; } // disk caching of queries $this->store_cache($query, $is_insert); // If debug ALL queries $this->trace || $this->debug_all ? $this->debug() : null; return $return_value; }
function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) { // seems that oracle only supports 1 hint comment in 8i if ($this->firstrows) { if (strpos($sql,'/*+') !== false) $sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql); else $sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql); } if ($offset < $this->selectOffsetAlg1 && 0 < $nrows && $nrows < 1000) { if ($nrows > 0) { if ($offset > 0) $nrows += $offset; //$inputarr['adodb_rownum'] = $nrows; if ($this->databaseType == 'oci8po') { $sql = "select * from (".$sql.") where rownum <= ?"; } else { $sql = "select * from (".$sql.") where rownum <= :adodb_offset"; } $inputarr['adodb_offset'] = $nrows; $nrows = -1; } // note that $nrows = 0 still has to work ==> no rows returned $rs = ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); return $rs; } else { // Algorithm by Tomas V V Cox, from PEAR DB oci8.php // Let Oracle return the name of the columns $q_fields = "SELECT * FROM (".$sql.") WHERE NULL = NULL"; $false = false; if (! $stmt_arr = $this->Prepare($q_fields)) { return $false; } $stmt = $stmt_arr[1]; 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, OCI_DEFAULT)) { OCIFreeStatement($stmt); return $false; } $ncols = OCINumCols($stmt); for ( $i = 1; $i <= $ncols; $i++ ) { $cols[] = '"'.OCIColumnName($stmt, $i).'"'; } $result = false; OCIFreeStatement($stmt); $fields = implode(',', $cols); $nrows += $offset; $offset += 1; // in Oracle rownum starts at 1 if ($this->databaseType == 'oci8po') { $sql = "SELECT $fields FROM". "(SELECT rownum as adodb_rownum, $fields FROM". " ($sql) WHERE rownum <= ?". ") WHERE adodb_rownum >= ?"; } else { $sql = "SELECT $fields FROM". "(SELECT rownum as adodb_rownum, $fields FROM". " ($sql) WHERE rownum <= :adodb_nrows". ") WHERE adodb_rownum >= :adodb_offset"; } $inputarr['adodb_nrows'] = $nrows; $inputarr['adodb_offset'] = $offset; if ($secs2cache>0) $rs = $this->CacheExecute($secs2cache, $sql,$inputarr); else $rs = $this->Execute($sql,$inputarr); return $rs; } }
function db_fieldname($lhandle,$fnumber) { return OCIColumnName($lhandle, $fnumber+1); }