Skip to content

Instantly share code, notes, and snippets.

@robsonpiere
Last active August 16, 2018 19:26
Show Gist options
  • Save robsonpiere/b115d80daa8927fdb4f0ea3ddc445fd0 to your computer and use it in GitHub Desktop.
Save robsonpiere/b115d80daa8927fdb4f0ea3ddc445fd0 to your computer and use it in GitHub Desktop.
Execute Stored Procedure - MSSQL - Codeignaiter 3
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Model extends CI_Model
{
public function __construct()
{
parent::__construct();
}
/**
* Executa uma SP de forma simples
*
* @param string $sql chamada para uma procedure
* @param array $params array(chave valor) com paramêtros da procedure
* @return CI_DB_pdo_result resultado de query do Codeignaiter
*/
function execute($sql, $params = [])
{
$sql = "execute $sql";
$sep = "";
foreach ($params as $key => $value) {
$sql .= "$sep $key = ?";
$sep = ',';
}
return $this->db->query($sql, $params);
}
/**
* Executa uma stored procedure que retorna multiplas tabelas
*
* @param string $sql chamada para uma procedure
* @param array $params array(chave valor) com paramêtros da procedure
* @return array array com resultados
* @throws UnexpectedValueException em caso de erro na query
*/
function execute_multi_result($sql, $params = [])
{
$sql = "execute $sql";
$sep = "";
foreach ($params as $key => $value) {
$sql .= "$sep $key = ".$this->db->escape($value);
$sep = ',';
}
$query = $this->db->simple_query($sql);
if (!$query) {
throw new UnexpectedValueException("Erro ao executar a consulta: $sql");
}
$results = [];
do {
$result = $query->fetchAll(PDO::FETCH_OBJ);
if ($result) {
array_push($results, $result);
}
} while ($query->nextRowset());
return $results;
}
}
@robsonpiere
Copy link
Author

robsonpiere commented Aug 16, 2018

Exemplo:

$parametros = ['@X' => $X , '@Y' => $Y];
$procedure = $this->execute('SP_SUAPROCEDURE', $parametros);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment