error getting data procedure in codeigniter - php

I created a stored procedure, which saves values ​​in a table temporal.y then I show with the "select " but only in my sqlserver works well . when you call the procedure in codeigniter I generated an empty array.
THIS IS MY PROCEDURE IN CODEIGNITER
function verificacion_ocupados($codigo,$llave_maestra){
$sql = "sp_verificacionocupados ?, ?";
$query = $this->db->query($sql,array($codigo, $llave_maestra));
$data = $query->result();
$query->free_result();
return $data;
}
THIS IS MY PROCEDURE
CREATE PROCEDURE [dbo].[sp_verificacionocupados]
#codigo int,
#llave_maestro varchar(50)
AS
DECLARE #finicio date;
DECLARE #ffinal date;
DECLARE #codigo_dias int;
DECLARE #no VARCHAR(100);
create table #pivote(
code int
);
SET #no='veremos';
BEGIN
SELECT #ffinal=Oel_Fecha_Fin,#finicio=Oel_Fecha_Inicio
FROM Operaciones_Especiales_Llave
where Em_Codigo=#codigo and Oel_Estado=2 and Th_Llave=#llave_maestro ;
IF ##ROWCOUNT>0
BEGIN
INSERT INTO #pivote VALUES (2);
END
END
SELECT code from #pivote;
GO
This is just one example of a much larger consultation I am doing .
I think the problem is in the temporary table and as I call to return data.
Who has an idea what is the problem ? . Thanks in advance

change it as following.
function verificacion_ocupados($codigo,$llave_maestra)
{
$sql="sp_verificacionocupadose ?, ?";
$query=$this->db->query('call sp_verificacionocupadose("$codigo","$llave_maestra")'));
$data=$query->result();
$query->free_result();
return $data;
}

Related

Calling stored procedures in Laravel 5.5 using SQL Server with output

I have the following stored procedure:
declare #CodigoRet int
exec Generator 'LancaContaContabil', #Codigo = #CodigoRet output
Select #CodigoRet
OBS: the LancaContaContabil is my table and the Codigo is the PK for that table
And I'm trying to call this procedure in Laravel 5.5 but it gives me the error: "The active result for the query contains no fields":
$results = DB::select(DB::raw('DECLARE #CodigoRet INT; execute Generator
\'LancaContaContabil\', #Codigo = #CodigoRet OUTPUT;'));
echo $results;
die;
Same error using the variant without dbraw:
$results = DB::select('DECLARE #CodigoRet INT; EXEC Generator
\'LancaContaContabil\', #Codigo = #CodigoRet OUTPUT;');
echo $results;
die;
Also tried with statement, but the return is always 1:
$results = DB::statement('DECLARE #CodigoRet INT; EXEC Generator
\'LancaContaContabil\', #Codigo = #CodigoRet OUTPUT;');
echo $results;
die;
EDIT: I created the procedure under the name 'testeproc' and now i've tried this, with the same error as above:
$results = DB::select('EXECUTE testeproc');
echo $results;
die;
What am I doing wrong?
I just got it sorted out. I will post here the solution that can help other people with the same problem.
$dbh = DB::connection()->getPdo();
$sth = $dbh->prepare("SET NOCOUNT ON; EXEC ProcLancaContaContabil");
$sth->execute();
$codigo = $sth->fetchAll(PDO::FETCH_COLUMN, 0);
The trick is to use "SET NOCOUNT ON" before calling the procedure.
I found this here
try this:
Without parameter:
$results = DB::select('EXEC your_stored_procedure');
Wit parameters
$results = DB::select('exec your_stored_procedure("parameter1", "parameter2",..)');
or
$results = DB::select('exec your_stored_procedure(?,?,..)',array($parameter1,$parameter2));
Here is a sample Stored Procedure:
CREATE PROCEDURE ReturnIdExample
(
#paramOne int
,#paramTwo nvarchar(255)
)
AS
SET NOCOUNT ON; --IMPORTANT!
BEGIN
-- Grab the id that was just created
DECLARE #ObjectID int;
INSERT INTO [Table]
(
[ColumnNameA]
,[ColumnNameB]
) VALUES (
#paramOne
,#paramTwo
)
SET #ObjectID = SCOPE_IDENTITY();
-- Select the id to return it back to laravel
SELECT#ObjectID AS ObjectID;
END
Calling this Stored Procedure in Laravel Model/Controller:
$submit = DB::select("EXEC ReturnIdExample ?,?", array( $paramOne ,$paramTwo ) );
Accessing the Return Variable in Laravel Model:
return $submit[0]->ObjectId;

error code 1414 occurs in mysql when i call stored procedure with ouput parameter

I'm trying to call a stored procedure (SP) from my codeigniter code but one of the parameters I defined in the Mysql SP is a OUTPUT parameter which is giving me some issues when calling the SP. Does anyone know the correct way to call the Sp from the PHP code with a OUTPUT parameter involved. The code is below:
MySql:
DROP PROCEDURE IF EXISTS usp_check_user_exist;
DELIMITER $$
CREATE PROCEDURE usp_check_user_exist
( IN email VARCHAR(200),
OUT result BIT(1) )
BEGIN
SET result = EXISTS(SELECT 1 FROM tbl_users WHERE user_email = email
LIMIT 1);
SELECT result;
END
Codeigniter/php:
public function check_email($email) {
$data = array(
'email' => $email,
'#result' => #result
);
$sp = "CALL usp_check_user_exist (?,?)";
$result = $this->db->query($sp, $data);
if($result) {
return TRUE;
} else {
return FALSE;
}
}
The error I got:
You have error in your stored procedure. Please check correct defination described below.
DELIMITER $$
DROP PROCEDURE `usp_check_user_exist`$$
CREATE PROCEDURE `usp_check_user_exist`(IN email VARCHAR(200))
BEGIN
DECLARE result TINYINT DEFAULT 0;
SET result = EXISTS(SELECT 1 FROM tbl_users WHERE user_email = email 1);
SELECT result;
END$$
DELIMITER ;
Also if you want to user your current Stored Procedure than while calling from PHP use statement like describe below.
call usp_check_user_exist('example#domain.com',#out);
Let me know if it not works.

how to select store procedure function genereteID in codeigniter?

I want to make a generated ID to use the function store procedure, but I am confused how to display generete ID using CodeIgniter.
Generete ID in store procedure function 'PenjualanGenIdFunc':
BEGIN
DECLARE kodebaru CHAR(15);
DECLARE urut INT;
SET urut = IF(nomer IS NULL, 1, nomer + 1);
SET kodebaru = CONCAT("PJL", LPAD(urut, 12, 0));
RETURN kodebaru;
END
I call in model with the code:
function getKodePenjualan(){
$query = $this->db->query("select PenjualanGenIdFunc('kodebaru') AS kodepenjualan");
return $query->row_array();
}
in controller :
$data['kodepenjualan'] = $this->mwebsite->getKodePenjualan();
and in view :
<?php echo $kodepenjualan['kodepenjualan'];?>
From the above code, generate ID already show with code: PJL000000000001, but when I will buy again. the code would not be PJL000000000002, PJL000000000003 and etc.
how to call a store procedure function for generete id ??
Please help me
First, if you want to call a SP, you need to call like this
$this->db->query("call PenjualanGenIdFunc()");
In your SP you must have something like this
CREATE PROCEDURE My_Insert
BEGIN
INSERT INTO My_Table (col1)
VALUES (#col1)
SELECT #new_identity = SCOPE_IDENTITY()
SELECT #new_identity AS id
RETURN
END
but if you want to get the last id insert using CI, you can use
$this->db->insert('table', array('value1' => $value1));
return $this->db->insert_id();

Migration script in MySQL

I want to do a Migration data from one table to another.
I wrote a simple PHP script for my purposes but I wanted to do this by MySql script using user defined variables:
the PHP script looks like this:
//MIGRATION
$sql = "SELECT position FROM ts_user_config WHERE position != '' AND position NOT REGEXP '^-?[0-9]+$' GROUP BY TRIM(position) ORDER BY position";
$positions = db_loadColumn( $sql );
foreach ($positions as $key => $pos) {
$sql = "SELECT id FROM user_positions where UPPER(position) = UPPER('$pos')";
$posId = db_loadResult($sql);
if ($posId == null) {
$sql = "INSERT INTO user_positions (position, `desc`) VALUES ('$pos', '$pos')";
db_exec($sql);
$posId = db_insert_id();
}
$sql = "UPDATE ts_user_config SET position='$posId' WHERE TRIM(position)='$pos'";
db_exec($sql);
}
//---------
Could somebody be so kind and rewrite this PHP instructions to MySQL script? I tried to do this but my mySQL knowledge is very low and I couldn't done that.
Please help me if its not too much effort.
Thank you in advance.
I Have DONE IT !!!!!! :)
this is my mySQL script, I dont know if its perfect but its do what I need. Please tell me if I can make something better here. Thanks again :)
drop procedure if exists PositionMigration;
delimiter '//'
CREATE PROCEDURE PositionMigration()
BEGIN
BLOCK1: BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE pos VARCHAR(100);
DECLARE posId1 INT;
DECLARE posId2 INT;
DECLARE sql1 CURSOR FOR SELECT position FROM ts_user_config WHERE position != '' AND position NOT REGEXP '^-?[0-9]+$' GROUP BY TRIM(position) ORDER BY position;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN sql1;
read_loop: LOOP
FETCH sql1 INTO pos;
IF done THEN
LEAVE read_loop;
END IF;
BLOCK2: BEGIN
DECLARE posNotFound INT DEFAULT FALSE;
DECLARE sql2 CURSOR FOR SELECT id FROM user_positions where UPPER(position) = UPPER(pos);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET posNotFound = TRUE;
OPEN sql2;
FETCH sql2 INTO posId1;
IF posNotFound THEN
INSERT INTO user_positions (position, \`desc\`) VALUES (pos, pos);
BLOCK3: BEGIN
DECLARE sql3 CURSOR FOR SELECT LAST_INSERT_ID();
OPEN sql3;
FETCH sql3 INTO posId2;
UPDATE ts_user_config SET position=posId2 WHERE TRIM(position)=pos;
CLOSE sql3;
END BLOCK3;
ELSE
UPDATE ts_user_config SET position=posId1 WHERE TRIM(position)=pos;
END IF;
CLOSE sql2;
END BLOCK2;
END LOOP;
CLOSE sql1;
END BLOCK1;
END;
//
delimiter ';'
call PositionMigration();

Mysql Stored Procedure and Php

I have created this procedure:
DROP PROCEDURE IF EXISTS add_com;
DELIMITER //
CREATE PROCEDURE add_com (cd CHAR(16), n VARCHAR(20), t VARCHAR(20), i VARCHAR(20))
BEGIN
DECLARE num INT;
DECLARE msg varchar(20);
set #num=select COUNT(*) from commercianti where codice_fiscale=cd;
IF num==0 THEN
insert into commercianti values (cd,n,i,t);
set #msg="Commerciante inserito";
ELSE
insert into errors values (1);
set #msg="Commerciante presente";
END IF;
return #msg;
END; //
then in a PHP page I execute this code:
<?php
$cd=$_POST['codice_fiscale'];
$n=$_POST['nominativo'];
$t=$_POST['telefono'];
$i=$_POST['indirizzo'];
if(!$cd||!$n||!$t||!$i)
echo "No data";
else{
require dirname(__FILE__) . '/' . 'dbconfig.php';
$mysqli = new MySQLI(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$result = $mysqli->query("CALL add_com('$cd','$n','$t','$i')");
echo $result;
}
?>
But the value of $result is undefined and seems the procedure doesn't work or isn't called.
If you want to get data back from a routine, you should be using a function, rather than a procedure. They have nearly the same syntax, but most notably is the RETURNS type section of the declaration. Take a look at the official documentation:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Note that the SECOND create block there is the one regarding functions. The first deals with procedures.
So I think that would look something like this:
DROP FUNCTION IF EXISTS add_com;
DELIMITER //
CREATE FUNCTION add_com (cd CHAR(16), n VARCHAR(20), t VARCHAR(20), i VARCHAR(20))
RETURNS VARCHAR(20)
BEGIN
DECLARE num INT;
DECLARE msg varchar(20);
SELECT COUNT(*) INTO #num FROM commercianti WHERE codice_fiscale = cd;
IF num==0 THEN
insert into commercianti values (cd,n,i,t);
set #msg="Commerciante inserito";
ELSE
insert into errors values (1);
set #msg="Commerciante presente";
END IF;
return #msg;
END; //
I'm not 100% sure about the RETURNS VARCHAR(20). That might have to be simply RETURNS VARCHAR.
Try changing
IF num==0 THEN
to
IF num=0 THEN

Categories