예제 #1
0
파일: SQLUtils.php 프로젝트: zekuny/RTPUI
/**
 * Execute Query to obtain one or more objects from the NECLIMS db; returns string on error
 *
 * @param $sql
 * @param optional class specification
 */
function query($sql, $object = NULL)
{
    // include object class if specifed
    if ($object != NULL) {
        require_once $object . ".cls.php";
    }
    // create a data access object
    $dao = new DAO();
    // pass the sql statement to the data access object
    $dao->setSQL($sql);
    // declare an array for storing the row results
    $retVal = array();
    try {
        // run the sql statement
        if ($dao->execute() && sqlsrv_has_rows($dao->getResultSet())) {
            // object specified.
            if ($object != NULL) {
                // while there were more results/rows, save the object in the array
                while ($row = sqlsrv_fetch_object($dao->getResultSet(), $object . "")) {
                    $retVal[] = $row;
                }
            } else {
                // while there were more results/rows, save the object in the array
                while ($row = sqlsrv_fetch_array($dao->getResultSet(), SQLSRV_FETCH_ASSOC)) {
                    $retVal[] = $row;
                }
            }
        }
    } catch (Exception $e) {
        return "Query Error: " . $e->getMessage() . ". SQL: " . $sql . ". Object specified: " . $object;
    }
    // return to the caller
    return $retVal;
    //error_log(print_r($retVal, true));
}
예제 #2
0
function GetFacultyQuestions($groupid)
{
    include_once 'db_Connection.php';
    $conn = sqlsrv_connect($serverName, $connectionInfo);
    $questionvalues = array();
    $questions = array();
    $faculty = array();
    $facultyquestions = array();
    if ($conn) {
        //----get acadyear-------------------
        $acid = 0;
        $sqlstr = " SELECT [AcadYearID] FROM [dbo].[Groups] where [groupid]=? ";
        $params = array($groupid);
        $sqlquery = sqlsrv_query($conn, $sqlstr, $params);
        if ($sqlquery) {
            while ($row = sqlsrv_fetch_array($sqlquery, SQLSRV_FETCH_ASSOC)) {
                $acid = $row['AcadYearID'];
            }
            sqlsrv_free_stmt($sqlquery);
        }
        $sqlstr = " SELECT [questionTypeId],[value],[text] " . " FROM [dbo].[QuestionValues] " . " order by questionTypeId ";
        //  $params = array ($acid);
        $sqlquery = sqlsrv_query($conn, $sqlstr);
        if ($sqlquery) {
            while ($row = sqlsrv_fetch_object($sqlquery)) {
                $questionvalues[] = $row;
            }
            sqlsrv_free_stmt($sqlquery);
        }
        //----get question array-------------------
        $sqlstr = " SELECT [QuestionID],[QueastionText],[questionType],[maxmark],-1 as mark,'' as description " . " FROM [dbo].[Questions] " . " where [QuestionLecturer]=0 " . " and [Acadyear]=? ";
        $params = array($acid);
        $sqlquery = sqlsrv_query($conn, $sqlstr, $params);
        if ($sqlquery) {
            while ($row = sqlsrv_fetch_object($sqlquery)) {
                $row->questionValues = array();
                foreach ($questionvalues as &$questValue) {
                    if ($questValue->questionTypeId === $row->questionType) {
                        array_push($row->questionValues, $questValue);
                    }
                }
                $questions[] = $row;
            }
            sqlsrv_free_stmt($sqlquery);
        }
        //----get faculty-------------------
        $sqlstr = " SELECT [FacultyID],[FacultyName] FROM [dbo].[Groups] " . " where [groupid]=? ";
        $params = array($groupid);
        $sqlquery = sqlsrv_query($conn, $sqlstr, $params);
        if ($sqlquery) {
            while ($row = sqlsrv_fetch_object($sqlquery)) {
                $row->quests = $questions;
                $faculty[] = $row;
            }
            $facultyquestions = array("result" => 0, "data" => $faculty);
        }
        sqlsrv_close($conn);
    }
    return $facultyquestions;
}
예제 #3
0
 /**
  * Enviar query para metodo query e devolve resultados como objecto
  *
  * @param string $query sql query
  *
  * @return object
  */
 public function results_object($query)
 {
     $this->query($query);
     $results = array();
     while ($res = sqlsrv_fetch_object($this->_query)) {
         $results[] = $res;
     }
     return $results;
 }
예제 #4
0
 /**
  * @return stdClass|bool
  */
 public function fetchObject()
 {
     $res = $this->result;
     if ($this->mSeekTo !== null) {
         $result = sqlsrv_fetch_object($res, 'stdClass', [], SQLSRV_SCROLL_ABSOLUTE, $this->mSeekTo);
         $this->mSeekTo = null;
     } else {
         $result = sqlsrv_fetch_object($res);
     }
     // Return boolean false when there are no more rows instead of null
     if ($result === null) {
         return false;
     }
     return $result;
 }
예제 #5
0
 public function loadObjectList($key = '', $class = 'stdClass')
 {
     //  $this->connect();
     $array = array();
     $stmt = $this->execute();
     if ($stmt === false) {
         return null;
     }
     // Get all of the rows from the result set as objects of type $class.
     while ($obj = sqlsrv_fetch_object($stmt)) {
         $array[] = $obj;
     }
     //   $this->close();
     //var_dump($array);
     return $array;
 }
예제 #6
0
파일: sqlsrv.php 프로젝트: wattanar/sqlsrv
 public static function queryArrayObject($connection, $query, $params = NULL)
 {
     if (!$params) {
         $query = sqlsrv_query($connection, $query);
     } else {
         $query = sqlsrv_query($connection, $query, $params);
     }
     if ($query) {
         $array_object = [];
         while ($fetch = sqlsrv_fetch_object($query)) {
             $array_object[] = $fetch;
         }
         return $array_object;
     } else {
         return;
     }
 }
예제 #7
0
 public function current()
 {
     if ($this->_current_row !== $this->_internal_row and !$this->seek($this->_current_row)) {
         return FALSE;
     }
     // Increment internal row for optimization assuming rows are fetched in order
     $this->_internal_row++;
     if ($this->_as_object === TRUE) {
         // Return an stdClass
         return sqlsrv_fetch_object($this->_result);
     } elseif (is_string($this->_as_object)) {
         // Return an object of given class name
         return sqlsrv_fetch_object($this->_result, $this->_as_object, $this->_object_params);
     } else {
         // Return an array of the row
         return sqlsrv_fetch_array($this->_result, SQLSRV_FETCH_ASSOC);
     }
 }
예제 #8
0
function data_select($qry, $query_params, $field_list)
{
    global $conn;
    $returnRecords = array();
    $rst = sqlsrv_query($conn, $qry, $query_params);
    sql_errors_display();
    $first_row = 1;
    while ($row = sqlsrv_fetch_object($rst)) {
        foreach ($row as $key => $value) {
            //echo('  field in row is: ' . $key);
            // loop through values
        }
        foreach ($field_list as $field) {
            $rowItem[$field] = $row->{$field};
        }
        $returnRecords[] = $rowItem;
    }
    return $returnRecords;
}
예제 #9
0
파일: sqlsrv.php 프로젝트: klas/joomla-cms
 /**
  * Method to fetch a row from the result set cursor as an object.
  *
  * @param   mixed   $cursor  The optional result set cursor from which to fetch the row.
  * @param   string  $class   The class name to use for the returned row object.
  *
  * @return  mixed   Either the next row from the result set or false if there are no more rows.
  *
  * @since   12.1
  */
 protected function fetchObject($cursor = null, $class = 'stdClass')
 {
     return sqlsrv_fetch_object($cursor ? $cursor : $this->cursor, $class);
 }
예제 #10
0
 /**
  * Result - object
  *
  * Returns the result set as an object
  *
  * @access	private
  * @return	object
  */
 function _fetch_object()
 {
     return sqlsrv_fetch_object($this->result_id);
 }
예제 #11
0
 if (!$stmt) {
     die('error' . mysql_error());
 }
 //取得したデータを配列に格納d
 while ($row = sqlsrv_fetch_object($stmt)) {
     $ship_name = $row->ship_name;
     $ship_picture = $row->ship_picture;
     $id = $row->ship_id;
     //$sql1 = "select top 1 * from sending_information where ship_id = '$id' and time between (now() - interval 2 hour ) and now() order by id desc;";
     //現在時刻から1日前 今は2時間前ができていない
     $sql1 = "select top 1 * from sending_information where ship_id = '{$id}' order by id desc;";
     $stmt1 = sqlsrv_query($dbh, $sql1);
     if (!$stmt1) {
         die('error' . mysql_error());
     }
     while ($row1 = sqlsrv_fetch_object($stmt1)) {
         $kakudo = $row1->direction;
         if (11.25 <= $kakudo && $kakudo < 33.75) {
             //船の方角 switch文が使えなかったかなしみ うまく動かなかった
             $kakudo = "北北東";
         } else {
             if (33.75 <= $kakudo && $kakudo < 56.25) {
                 $kakudo = "北東";
             } else {
                 if (56.25 <= $kakudo && $kakudo < 78.75) {
                     $kakudo = "東北東";
                 } else {
                     if (78.75 <= $kakudo && $kakudo < 101.25) {
                         $kakudo = "東";
                     } else {
                         if (101.25 <= $kakudo && $kakudo < 123.75) {
예제 #12
0
 function query($query)
 {
     //if flag to convert query from MySql syntax to MS-Sql syntax is true
     //convert the query
     if ($this->convertMySqlToMSSqlQuery == true) {
         $query = $this->ConvertMySqlToMSSql($query);
     }
     // Initialise return
     $return_val = 0;
     // Flush cached values..
     $this->flush();
     // For reg expressions
     $query = trim($query);
     // Log how the function was called
     $this->func_call = "\$db->query(\"{$query}\")";
     // Keep track of the last query for debug..
     $this->last_query = $query;
     // Count how many queries there have been
     $this->num_queries++;
     // 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, $this->dbhost);
     }
     // Perform the query via std mssql_query function..
     $this->result = @sqlsrv_query($this->dbh, $query);
     // If there is an error then take note of it..
     if ($this->result === false) {
         $errors = sqlsrv_errors();
         if (!empty($errors)) {
             $is_insert = true;
             foreach ($errors as $error) {
                 $sqlError = "ErrorCode: " . $error['code'] . " ### State: " . $error['SQLSTATE'] . " ### Error Message: " . $error['message'] . " ### Query: " . $query;
                 $this->register_error($sqlError);
                 $this->show_errors ? trigger_error($sqlError, E_USER_WARNING) : null;
             }
         }
         return false;
     }
     // Query was an insert, delete, update, replace
     $is_insert = false;
     if (preg_match("/^(insert|delete|update|replace)\\s+/i", $query)) {
         $this->rows_affected = @sqlsrv_rows_affected($this->dbh);
         // Take note of the insert_id
         if (preg_match("/^(insert|replace)\\s+/i", $query)) {
             $identityresultset = @sqlsrv_query($this->dbh, "select SCOPE_IDENTITY()");
             if ($identityresultset != false) {
                 $identityrow = @sqlsrv_fetch($identityresultset);
                 $this->insert_id = $identityrow[0];
             }
         }
         // Return number of rows affected
         $return_val = $this->rows_affected;
     } else {
         // Take note of column info
         $i = 0;
         foreach (@sqlsrv_field_metadata($this->result) as $field) {
             foreach ($field as $name => $value) {
                 $name = strtolower($name);
                 if ($name == "size") {
                     $name = "max_length";
                 } else {
                     if ($name == "type") {
                         $name = "typeid";
                     }
                 }
                 $col->{$name} = $value;
             }
             $col->type = $this->get_datatype($col);
             $this->col_info[$i++] = $col;
             unset($col);
         }
         // Store Query Results
         $num_rows = 0;
         while ($row = @sqlsrv_fetch_object($this->result)) {
             // Store relults as an objects within main array
             $this->last_result[$num_rows] = $row;
             $num_rows++;
         }
         @sqlsrv_free_stmt($this->result);
         // Log number of rows the query returned
         $this->num_rows = $num_rows;
         // Return number of rows selected
         $return_val = $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_val;
 }
예제 #13
0
 public function getPO($filter)
 {
     $conn = SapConfig::msqlconn();
     $tn = SapConfig::$getTable;
     $fnumb = SapConfig::$funcNumber;
     if ($conn) {
         $stmt = "SELECT {$tn}.VBAK.BSTNK, {$tn}.VBAK.BSTDK FROM {$tn}.VBAK WHERE {$tn}.VBAK.VBELN ='" . $filter . "' AND {$tn}.VBAK.MANDT = {$fnumb}";
         if (($result = sqlsrv_query($conn, $stmt)) !== false) {
             $return_value = array();
             while ($obj = sqlsrv_fetch_object($result)) {
                 array_push($return_value, $obj);
             }
             return $return_value;
         }
     } else {
         echo "Connection could not be established.<br />";
         die(print_r(sqlsrv_errors(), true));
     }
 }
function GetScheduleWithQuestions($groupid)
{
    include_once 'db_Connection.php';
    $conn = sqlsrv_connect($serverName, $connectionInfo);
    $questionvalues = array();
    $questions = array();
    $schedule = array();
    $schedulequestions = array();
    if ($conn) {
        //----get acadyear-------------------
        $acid = 0;
        $sqlstr = " SELECT [AcadYearID] FROM [dbo].[Groups] where [groupid]=? ";
        $params = array($groupid);
        $sqlquery = sqlsrv_query($conn, $sqlstr, $params);
        if ($sqlquery) {
            while ($row = sqlsrv_fetch_array($sqlquery, SQLSRV_FETCH_ASSOC)) {
                $acid = $row['AcadYearID'];
            }
            sqlsrv_free_stmt($sqlquery);
        }
        $sqlstr = " SELECT [questionTypeId],[value],[text] " . " FROM [dbo].[QuestionValues] " . " order by questionTypeId ";
        //  $params = array ($acid);
        $sqlquery = sqlsrv_query($conn, $sqlstr);
        if ($sqlquery) {
            while ($row = sqlsrv_fetch_object($sqlquery)) {
                $questionvalues[] = $row;
            }
            sqlsrv_free_stmt($sqlquery);
        }
        //----get question array-------------------
        $sqlstr = " SELECT [QuestionID],[QueastionText],[questionType],[maxmark],[NeedDescription],-1 as mark,'' as description " . " FROM [dbo].[Questions] " . " where [QuestionLecturer]=1 " . " and [Acadyear]=? ";
        $params = array($acid);
        $sqlquery = sqlsrv_query($conn, $sqlstr, $params);
        if ($sqlquery) {
            while ($row = sqlsrv_fetch_object($sqlquery)) {
                $row->questionValues = array();
                foreach ($questionvalues as &$questValue) {
                    if ($questValue->questionTypeId === $row->questionType) {
                        array_push($row->questionValues, $questValue);
                    }
                }
                $questions[] = $row;
            }
            sqlsrv_free_stmt($sqlquery);
        }
        //----get schadule array-------------------
        $sqlstr = " SELECT distinct [SubjID],[SubjName],[STypeID],[STypeName],0 as SelectedLectID " . " FROM [dbo].[Schedule] " . " WHERE groupID=? " . " order by [SubjID],[STypeID] ";
        $params = array($groupid);
        $sqlquery = sqlsrv_query($conn, $sqlstr, $params);
        if ($sqlquery) {
            while ($row = sqlsrv_fetch_object($sqlquery)) {
                $sb = $row->SubjID;
                $st = $row->STypeID;
                $row->lect = array();
                $sqlstr = " SELECT distinct [LectID],[LectName] " . " FROM [dbo].[Schedule] " . " WHERE groupID=? " . " and subjID=? " . " and STypeID=? ";
                $params = array($groupid, $sb, $st);
                $sqlquerylect = sqlsrv_query($conn, $sqlstr, $params);
                if ($sqlquerylect) {
                    while ($rowlect = sqlsrv_fetch_object($sqlquerylect)) {
                        //                  	  foreach ($row->lect as $lect)
                        //                    {
                        $rowlect->quests = $questions;
                        // array_push(   $rowlect->quests,$questions);
                        array_push($row->lect, $rowlect);
                        //                    }
                    }
                }
                $schedule[] = $row;
            }
        }
    }
    $schedulequestions = array("result" => 0, "data" => $schedule);
    return $schedulequestions;
}
예제 #15
0
 /**
  * Method to fetch a row from the result set cursor as an object.
  *
  * @return  mixed   Either the next row from the result set or false if there are no more rows.
  *
  * @since   12.1
  */
 protected function fetchObject()
 {
     return sqlsrv_fetch_object($this->cursor, $this->class);
 }
예제 #16
0
 /**
  * Result - object
  *
  * Returns the result set as an object
  *
  * @param	string	$class_name
  * @return	object
  */
 protected function _fetch_object($class_name = 'stdClass')
 {
     return sqlsrv_fetch_object($this->result_id, $class_name);
 }
예제 #17
0
									}
								}

									  if($distance<100000){

											$sql2="select top 1 * from ship_location where id > 814000 and ship_id = '$shipid' and emergency != 0  order by id desc;";
											$stmt2 = sqlsrv_query($dbh,$sql2);

												if (!$stmt2) {

													die('error'.mysql_error());

												}

												while($row2 = sqlsrv_fetch_object($stmt2))
												{
													$users[] = array(
														'lat'=> $row2->lat,
														'lon'=> $row2->lon,
														'ship_id'=> $row2->ship_id,
														'emergency'=> $row2->emergency,
														'distance'=> $distance,
														'flag'=>  "0",
														);
												}
									}else{
										$users[] = array(
											'flag'=>  "1",
											);
									}
 public function getObject()
 {
     if (!$this->query()) {
         return false;
     }
     $retval = sqlsrv_fetch_object($this->result);
     if ($retval === false) {
         return null;
     }
     return $retval;
 }
예제 #19
0
 /**
  * Perform a MySQL database query, using current database connection.
  *
  * More information can be found on the codex page.
  *
  * @since 0.71
  *
  * @param string $query Database query
  * @return int|false Number of rows affected/selected or false on error
  */
 public function query($query)
 {
     if (!$this->ready) {
         $this->check_current_query = true;
         return false;
     }
     /**
      * Filter the database query.
      *
      * Some queries are made before the plugins have been loaded,
      * and thus cannot be filtered with this method.
      *
      * @since 2.1.0
      *
      * @param string $query Database query.
      */
     $query = apply_filters('query', $query);
     $this->flush();
     // Log how the function was called
     $this->func_call = "\$db->query(\"{$query}\")";
     // If we're writing to the database, make sure the query will write safely.
     if ($this->check_current_query && !$this->check_ascii($query)) {
         $stripped_query = $this->strip_invalid_text_from_query($query);
         // strip_invalid_text_from_query() can perform queries, so we need
         // to flush again, just to make sure everything is clear.
         $this->flush();
         if ($stripped_query !== $query) {
             $this->insert_id = 0;
             return false;
         }
     }
     $this->check_current_query = true;
     // Keep track of the last query for debug..
     $this->last_query = $query;
     $this->_do_query($query);
     // MySQL server has gone away, try to reconnect
     /*
     		$mysql_errno = 0;
     		if ( ! empty( $this->dbh ) ) {
     			if ( $this->use_mysqli ) {
     				$mysql_errno = mysqli_errno( $this->dbh );
     			} else {
     				$mysql_errno = mysql_errno( $this->dbh );
     			}
     		}
     
     		if ( empty( $this->dbh ) || 2006 == $mysql_errno ) {
     			if ( $this->check_connection() ) {
     				$this->_do_query( $query );
     			} else {
     				$this->insert_id = 0;
     				return false;
     			}
     		}
     */
     // If there is an error, first attempt to translate
     $errors = sqlsrv_errors();
     if (!empty($errors) && is_array($errors)) {
         switch ($errors[0]['code']) {
             case 102:
             case 145:
             case 156:
             case 195:
             case 207:
             case 241:
             case 261:
             case 321:
             case 1018:
             case 8120:
             case 8127:
                 if (getenv('ProjectNamiLogTranslate')) {
                     $begintransmsg = date("Y-m-d H:i:s") . " -- Begin translation attempt: {$query} \n";
                     error_log($begintransmsg, 3, 'D:\\home\\LogFiles\\translate.log');
                 }
                 $sqltranslate = new SQL_Translations(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
                 $query = $sqltranslate->translate($query);
                 if (getenv('ProjectNamiLogTranslate')) {
                     $endtransmsg = date("Y-m-d H:i:s") . " -- Translation result: {$query} \n";
                     error_log($endtransmsg, 3, 'D:\\home\\LogFiles\\translate.log');
                 }
                 $this->last_query = $query;
                 $this->_do_query($query);
                 // If there is an error then take note of it..
                 $errors = sqlsrv_errors();
         }
     }
     if (!empty($errors) && is_array($errors)) {
         $this->last_error = $errors[0]['message'];
         // Clear insert_id on a subsequent failed insert.
         if ($this->insert_id && preg_match('/^\\s*(insert|replace)\\s/i', $query)) {
             $this->insert_id = 0;
         }
         $this->print_error();
         return false;
     }
     if (preg_match('/^\\s*(create|alter|truncate|drop)\\s/i', $query)) {
         $return_val = $this->result;
     } elseif (preg_match('/^\\s*(insert|delete|update|replace)\\s/i', $query) && $this->query_statement_resource != false) {
         $this->rows_affected = sqlsrv_rows_affected($this->query_statement_resource);
         // Take note of the insert_id
         if (preg_match('/^\\s*(insert|replace)\\s/i', $query)) {
             $this->insert_id = sqlsrv_query($this->dbh, 'SELECT isnull(scope_identity(), 0)');
             $row = sqlsrv_fetch_array($this->insert_id);
             $this->insert_id = $row[0];
         }
         // Return number of rows affected
         $return_val = $this->rows_affected;
     } else {
         $num_rows = 0;
         while ($row = @sqlsrv_fetch_object($this->query_statement_resource)) {
             $this->last_result[$num_rows] = $row;
             $num_rows++;
         }
         // Log number of rows the query returned
         // and return number of rows selected
         $this->num_rows = $num_rows;
         $return_val = $num_rows;
     }
     if (isset($this->last_result[0]) && is_object($this->last_result[0]) && isset($this->last_result[0]->found_rows)) {
         $this->last_query_total_rows = $this->last_result[0]->found_rows;
     }
     return $return_val;
 }
예제 #20
0
require_once "conn/connect.php";
$id = "";
if (isset($_GET['id'])) {
    $id = $_GET['id'];
}
//Actualizacion de visitas
$insert = " UPDATE DOCUMENTO SET DOCU_VISI=DOCU_VISI + 1 WHERE DOCU_ID = " . $id . "";
$params = array();
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$update = sqlsrv_query($conn, $insert, $params, $options);
//cargar datos del archivo
$sql = " SELECT * FROM DOCUMENTO WHERE  DOCU_ID  = " . $id . "";
$params = array();
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$resultado = sqlsrv_query($conn, $sql, $params, $options);
$fila = sqlsrv_fetch_object($resultado);
?>
<!DOCTYPE html>
<html lang ="en">
	<head>
		<title>Buscador de Documentos</title>
		<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
		<script type="text/javascript" src="js/ajax.js"></script>
		<link rel="stylesheet"  href="css/estilos.css">
		<link href="css/bootstrap.css" rel="stylesheet">
		<link href='https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700' rel='stylesheet' type='text/css'>
	</head>
	<body>
				<div class="container">

					<div class="center panel-orange shadow">
예제 #21
0
 /**
  * Fetch a result row as an object
  *
  * @param  resource $result Resultset
  * @return resource
  */
 public function fetchObject($result)
 {
     return sqlsrv_fetch_object($result);
 }
예제 #22
0
$servidor = sqlsrv_connect($url, $conninfo) or die("Não foi possível a conexão com o servidor!");
//1_Se elige el formato de datos para lla conexion UTF8
//Se prepara la peticion
//2_Se establece la consulta a la BD
$params = array();
$options = array("Scrollable" => SQLSRV_CURSOR_KEYSET);
$consulta = "SELECT * FROM opcionaisXdescricao where codigo='" . $cod . "' or codprod=" . $cod . "";
//echo "sql: ".$consulta;
//die();
$sql = sqlsrv_query($servidor, $consulta, $params, $options);
$row_count = sqlsrv_num_rows($sql);
//3_Se declara un arreglo
$datos = array();
//SE genera el archivo JSON
$i = 0;
while ($obj = sqlsrv_fetch_object($sql)) {
    //echo 'foi';
    $i = $i + 1;
    if ($i != $row_count) {
        $datos[] = array('opcional' => $obj->opcional . ",&nbsp;");
    } else {
        $datos[] = array('opcional' => $obj->opcional . ".");
    }
}
echo '' . json_encode($datos) . '';
sqlsrv_close($servidor);
//Se cierra la conexion
//Se declara que esta es una aplicacion que genera un JSON
header('Content-type: application/json');
//Se abre el acceso a las conexiones que requieran de esta aplicacion
header("Access-Control-Allow-Origin: *");
예제 #23
0
파일: adress.php 프로젝트: Ryu0621/SaNaVi
 $a = date('Y', strtotime($postatime));
 $b = date('d', strtotime($postatime));
 //DBに接続
 $dbh = sqlsrv_connect($serverName, $connectionInfo);
 $sql0 = "select top 12 * from Hack where animal = '{$postanimal_kind}' and date like  '%{$a}%' and date like  '%{$b}%' ORDER BY id DESC;";
 $stmt = sqlsrv_query($dbh, $sql0);
 if (!$stmt) {
     die('error' . mysql_error());
 }
 /*住所*/
 $p = urlencode($postadress);
 $xml = simplexml_load_file("http://www.geocoding.jp/api/?q={$p}");
 $latadress = $xml->coordinate->lat;
 $lonadress = $xml->coordinate->lng;
 //取得したデータを配列に格納
 while ($row = sqlsrv_fetch_object($stmt)) {
     $lat = $row->lat;
     $lon = $row->lon;
     $distance = 0;
     $lat1 = $latadress;
     $lng1 = $lonadress;
     $lat2 = $lat;
     $lng2 = $lon;
     if (abs($lat1 - $lat2) < 1.0E-5 && abs($lng1 - $lng2) < 1.0E-5) {
         $distance = 0;
     } else {
         $x = $lat2 - $lat1;
         $y = $lng2 - $lng1;
         $E = $x * 10000 * 11.32;
         $T = $y * 10000 * 9.228999999999999;
         $U = pow($E, 2);
예제 #24
0
파일: pdf.php 프로젝트: llanosCoder/mybu
 require '/fpdf/fpdf.php';
 $pdf = new FPDF('L');
 $pdf->AddPage();
 // Imagen
 $pdf->Image('serbimaAA.jpg', 245, 8, 30);
 // titulo
 $pdf->SetFont('Arial', 'B', 12);
 $pdf->SetXY(90, 10);
 $pdf->Write(1, "PLANILLA DE DESCUENTO {$emp}");
 $pdf->SetXY(125, 15);
 $pdf->Write(1, 'Mes de ' . $nombre_mes . ' del ' . $ano);
 // Informacion del empleador
 $pdf->SetFont('Arial', 'U', 10);
 $pdf->SetXY(10, 30);
 $pdf->Write(1, 'Información del empleador');
 if ($registro = sqlsrv_fetch_object($resultado)) {
     $rut_inst = $registro->rut_inst;
     $dv_inst = $registro->dv_inst;
 }
 function rut($rut)
 {
     return number_format(substr($rut, 0, -1), 0, "", ".") . '-' . substr($rut, strlen($rut) - 1, 1);
 }
 $rut_inst_formateado = rut($rut_inst . $dv_inst);
 $pdf->SetFont('Arial', 'B', 9);
 $pdf->SetXY(20, 40);
 $pdf->Write(1, 'R.U.T');
 $pdf->SetFont('Arial', '', 9);
 $pdf->SetXY(40, 40);
 $pdf->Write(1, $rut_inst_formateado);
 $pdf->SetFont('Arial', 'B', 9);
 /**
  * {@inheritdoc}
  */
 public function fetch($fetchMode = null)
 {
     $fetchMode or $fetchMode = $this->defaultFetchMode;
     if (isset(self::$fetchMap[$fetchMode])) {
         return sqlsrv_fetch_array($this->stmt, self::$fetchMap[$fetchMode]);
     } else {
         if ($fetchMode == PDO::FETCH_OBJ || $fetchMode == PDO::FETCH_CLASS) {
             $className = null;
             $ctorArgs = null;
             if (func_num_args() >= 2) {
                 $args = func_get_args();
                 $className = $args[1];
                 $ctorArgs = isset($args[2]) ? $args[2] : array();
             }
             return sqlsrv_fetch_object($this->stmt, $className, $ctorArgs);
         }
     }
     throw new SQLSrvException("Fetch mode is not supported!");
 }
예제 #26
0
 /**
  * fetch
  *
  * @see Doctrine_Core::FETCH_* constants
  * @param integer $fetchStyle           Controls how the next row will be returned to the caller.
  *                                      This value must be one of the Doctrine_Core::FETCH_* constants,
  *                                      defaulting to Doctrine_Core::FETCH_BOTH
  *
  * @param integer $cursorOrientation    For a PDOStatement object representing a scrollable cursor,
  *                                      this value determines which row will be returned to the caller.
  *                                      This value must be one of the Doctrine_Core::FETCH_ORI_* constants, defaulting to
  *                                      Doctrine_Core::FETCH_ORI_NEXT. To request a scrollable cursor for your
  *                                      Doctrine_Adapter_Statement_Interface object,
  *                                      you must set the Doctrine_Core::ATTR_CURSOR attribute to Doctrine_Core::CURSOR_SCROLL when you
  *                                      prepare the SQL statement with Doctrine_Adapter_Interface->prepare().
  *
  * @param integer $cursorOffset         For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for which the
  *                                      $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_ABS, this value specifies
  *                                      the absolute number of the row in the result set that shall be fetched.
  *
  *                                      For a Doctrine_Adapter_Statement_Interface object representing a scrollable cursor for
  *                                      which the $cursorOrientation parameter is set to Doctrine_Core::FETCH_ORI_REL, this value
  *                                      specifies the row to fetch relative to the cursor position before
  *                                      Doctrine_Adapter_Statement_Interface->fetch() was called.
  *
  * @return mixed
  */
 public function fetch($fetchStyle = Doctrine_Core::FETCH_BOTH, $cursorOrientation = Doctrine_Core::FETCH_ORI_NEXT, $cursorOffset = null)
 {
     if (!$this->statement) {
         return false;
     }
     switch ($fetchStyle) {
         case Doctrine_Core::FETCH_BOTH:
             return sqlsrv_fetch_array($this->statement, SQLSRV_FETCH_BOTH);
             break;
         case Doctrine_Core::FETCH_ASSOC:
             return sqlsrv_fetch_array($this->statement, SQLSRV_FETCH_ASSOC);
             break;
         case Doctrine_Core::FETCH_NUM:
             return sqlsrv_fetch_array($this->statement, SQLSRV_FETCH_NUMERIC);
             break;
         case Doctrine_Core::FETCH_OBJ:
             return sqlsrv_fetch_object($this->statement);
             break;
         default:
             throw new Doctrine_Adapter_Exception("This type of fetch is not supported: " . $fetchStyle);
             /*
                         case Doctrine_Core::FETCH_BOUND:
                         case Doctrine_Core::FETCH_CLASS:
                         case FETCH_CLASSTYPE:
                         case FETCH_COLUMN:
                         case FETCH_FUNC:
                         case FETCH_GROUP:
                         case FETCH_INTO:
                         case FETCH_LAZY:
                         case FETCH_NAMED:
                         case FETCH_SERIALIZE:
                         case FETCH_UNIQUE:
                            case FETCH_ORI_ABS:
                         case FETCH_ORI_FIRST:
                         case FETCH_ORI_LAST:
                         case FETCH_ORI_NEXT:
                         case FETCH_ORI_PRIOR:
                         case FETCH_ORI_REL:
             */
     }
 }
예제 #27
0
파일: SQLSRV.php 프로젝트: alab1001101/zf2
 /**
  * Fetches the next row and returns it as an object.
  *
  * @param string $class  OPTIONAL Name of the class to create.
  * @param array  $config OPTIONAL Constructor arguments for the class.
  * @return mixed One object instance of the specified class.
  * @throws \Zend\DB\Statement\Exception
  */
 public function fetchObject($class = 'stdClass', array $config = array())
 {
     if (!$this->_stmt) {
         return false;
     }
     $obj = sqlsrv_fetch_object($this->_stmt);
     if ($error = sqlsrv_errors()) {
         throw new Exception($error);
     }
     /* @todo XXX handle parameters */
     if (null === $obj) {
         return false;
     }
     return $obj;
 }
예제 #28
0
 /**
  * INSERT wrapper, inserts an array into a table
  *
  * $arrToInsert may be a single associative array, or an array of these with numeric keys, for
  * multi-row insert.
  *
  * Usually aborts on failure
  * If errors are explicitly ignored, returns success
  */
 function insert($table, $arrToInsert, $fname = 'DatabaseMssql::insert', $options = array())
 {
     # No rows to insert, easy just return now
     if (!count($arrToInsert)) {
         return true;
     }
     if (!is_array($options)) {
         $options = array($options);
     }
     $table = $this->tableName($table);
     if (!(isset($arrToInsert[0]) && is_array($arrToInsert[0]))) {
         // Not multi row
         $arrToInsert = array(0 => $arrToInsert);
         // make everything multi row compatible
     }
     $allOk = true;
     // We know the table we're inserting into, get its identity column
     $identity = null;
     $tableRaw = preg_replace('#\\[([^\\]]*)\\]#', '$1', $table);
     // strip matching square brackets from table name
     $res = $this->doQuery("SELECT NAME AS idColumn FROM SYS.IDENTITY_COLUMNS WHERE OBJECT_NAME(OBJECT_ID)='{$tableRaw}'");
     if ($res && $res->numrows()) {
         // There is an identity for this table.
         $identity = array_pop($res->fetch(SQLSRV_FETCH_ASSOC));
     }
     unset($res);
     foreach ($arrToInsert as $a) {
         // start out with empty identity column, this is so we can return it as a result of the insert logic
         $sqlPre = '';
         $sqlPost = '';
         $identityClause = '';
         // if we have an identity column
         if ($identity) {
             // iterate through
             foreach ($a as $k => $v) {
                 if ($k == $identity) {
                     if (!is_null($v)) {
                         // there is a value being passed to us, we need to turn on and off inserted identity
                         $sqlPre = "SET IDENTITY_INSERT {$table} ON;";
                         $sqlPost = ";SET IDENTITY_INSERT {$table} OFF;";
                     } else {
                         // we can't insert NULL into an identity column, so remove the column from the insert.
                         unset($a[$k]);
                     }
                 }
             }
             $identityClause = "OUTPUT INSERTED.{$identity} ";
             // we want to output an identity column as result
         }
         $keys = array_keys($a);
         // INSERT IGNORE is not supported by SQL Server
         // remove IGNORE from options list and set ignore flag to true
         $ignoreClause = false;
         foreach ($options as $k => $v) {
             if (strtoupper($v) == "IGNORE") {
                 unset($options[$k]);
                 $ignoreClause = true;
             }
         }
         // translate MySQL INSERT IGNORE to something SQL Server can use
         // example:
         // MySQL: INSERT IGNORE INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
         // MSSQL: IF NOT EXISTS (SELECT * FROM user_groups WHERE ug_user = '******') INSERT INTO user_groups (ug_user,ug_group) VALUES ('1','sysop')
         if ($ignoreClause) {
             $prival = $a[$keys[0]];
             $sqlPre .= "IF NOT EXISTS (SELECT * FROM {$table} WHERE {$keys['0']} = '{$prival}')";
         }
         // Build the actual query
         $sql = $sqlPre . 'INSERT ' . implode(' ', $options) . " INTO {$table} (" . implode(',', $keys) . ") {$identityClause} VALUES (";
         $first = true;
         foreach ($a as $value) {
             if ($first) {
                 $first = false;
             } else {
                 $sql .= ',';
             }
             if (is_string($value)) {
                 $sql .= $this->addQuotes($value);
             } elseif (is_null($value)) {
                 $sql .= 'null';
             } elseif (is_array($value) || is_object($value)) {
                 if (is_object($value) && strtolower(get_class($value)) == 'blob') {
                     $sql .= $this->addQuotes($value);
                 } else {
                     $sql .= $this->addQuotes(serialize($value));
                 }
             } else {
                 $sql .= $value;
             }
         }
         $sql .= ')' . $sqlPost;
         // Run the query
         $ret = sqlsrv_query($this->mConn, $sql);
         if ($ret === false) {
             throw new DBQueryError($this, $this->getErrors(), $this->lastErrno(), $sql, $fname);
         } elseif ($ret != NULL) {
             // remember number of rows affected
             $this->mAffectedRows = sqlsrv_rows_affected($ret);
             if (!is_null($identity)) {
                 // then we want to get the identity column value we were assigned and save it off
                 $row = sqlsrv_fetch_object($ret);
                 $this->mInsertId = $row->{$identity};
             }
             sqlsrv_free_stmt($ret);
             continue;
         }
         $allOk = false;
     }
     return $allOk;
 }
예제 #29
0
파일: Sqlsrv.php 프로젝트: Pengzw/c3crm
 /**
  * Fetches the next row and returns it as an object.
  *
  * @param string $class  OPTIONAL Name of the class to create.
  * @param array  $config OPTIONAL Constructor arguments for the class.
  * @return mixed One object instance of the specified class.
  * @throws Zend_Db_Statement_Exception
  */
 public function fetchObject($class = 'stdClass', array $config = array())
 {
     if (!$this->_stmt) {
         return false;
     }
     $obj = sqlsrv_fetch_object($this->_stmt);
     if ($error = sqlsrv_errors()) {
         require_once 'include/Zend/Db/Statement/Sqlsrv/Exception.php';
         throw new Zend_Db_Statement_Sqlsrv_Exception($error);
     }
     /* @todo XXX handle parameters */
     if (null === $obj) {
         return false;
     }
     return $obj;
 }
 /**
  * (non-PHPdoc)
  * @see classes/connectionengine/Result_STH#moveNext()
  */
 public function moveNext()
 {
     $this->row = sqlsrv_fetch_object($this->result);
     if ($this->row === false) {
         $this->EOF = true;
     } else {
         $this->EOF = false;
     }
 }