Don't know how to get values from stored procedure - php

I wrote a stored procedure this morning and I don't know how to get the values out of it through a class function in php or phpmyadmin. The other examples from the site was not helpful to me.
Here is what I wrote to get results:
public function totalProcedures($friend_name,$session_id)
{
/*
*query to fetch stored procedure
*/
try
{
//executing the stored procedure
$sql_sp="CALL timeline (:friend, :session,#updates, #group_posts)";
$stmt_sp= $this->_db->prepare($sql_sp);
$stmt_sp->bindValue(":friend",$friend_name);
$stmt_sp->bindValue(":session",$session_id);
$stmt_sp->execute();
$rows=$stmt_sp->fetch(PDO::FETCH_ASSOC);
$stmt_sp->closeCursor(); // closing the stored procedure
//trying to get values from OUT parameters.
$stmt_sp_2=$this->_db->prepare("select #updates,#group_posts");
$stmt_sp_2->execute();
return $stmt_sp_2->fetch(PDO::FETCH_ASSOC);
}
catch (PDOException $ei)
{
echo $ei->getMessage();
}
}
Can someone help me how to get results?
Here is the stored procedure:
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `timeline`(IN `friend` VARCHAR(255), IN `session_id` VARCHAR(255), OUT `updates` VARCHAR(62555), OUT `group_posts` VARCHAR(62555))
BEGIN
SELECT *
FROM updates
WHERE author IN (friend, session_id)
ORDER BY time DESC
LIMIT 5;
SELECT *
FROM group_posts
WHERE author_gp IN (friend, session_id)
ORDER BY pdate DESC
LIMIT 5;
END$$
DELIMITER ;

Related

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 do I CALL mysql TEMPORARY TABLE from CodeIgniter?

I have written a stored procedure in mysql which will create a TEMPORARY TABLE, I want to access the data of TEMPORARY TABLE using Codeigniter.But when I call "$this->db->query()" it returns empty data.
$data=array();
$call_procedure = "CALL sp_Stock()";
$query = $this->db->query($call_procedure);
$sql="SELECT * FROM StockTable";
$query1 = $this->db->query($sql);
I have changed my way to show the data. And I do changes it on stored procedure.
DELIMITER $$
CREATE PROCEDURE sp_Stock()
BEGIN
DECLARE cursor_finish INTEGER DEFAULT 0;
DECLARE m_numofpurchaseBag DECIMAL(10,2)DEFAULT 0;
DECLARE m_purchasedKg DECIMAL(10,2)DEFAULT 0;
DECLARE m_purBagDtlId INTEGER DEFAULT 0;
DECLARE stockCursor CURSOR FOR
SELECT purchase_bag_details.`actual_bags`,
(purchase_bag_details.`net`*purchase_bag_details.`actual_bags`) AS PurchasedKg,
purchase_bag_details.`id` AS PurchaseBagDtlId
FROM
purchase_invoice_detail
INNER JOIN
purchase_bag_details
ON purchase_invoice_detail.`id`= purchase_bag_details.`purchasedtlid`
INNER JOIN
`do_to_transporter`
ON purchase_invoice_detail.`id` = do_to_transporter.`purchase_inv_dtlid`
WHERE purchase_invoice_detail.`teagroup_master_id`=6
AND purchase_invoice_detail.`id`=1481
AND do_to_transporter.`in_Stock`='Y';
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET cursor_finish = 1;
DROP TEMPORARY TABLE IF EXISTS StockTable;
#temptable creation
CREATE TEMPORARY TABLE IF NOT EXISTS StockTable
(
purchaseBagDtlId INT,
purchasedBag NUMERIC(10,2),
purchasedKg NUMERIC(10,2),
blendedBag NUMERIC(10,2),
blendedKg NUMERIC(10,2),
stockBag NUMERIC(10,2),
stockKg NUMERIC(10,2)
);
#temptable creation
OPEN stockCursor ;
get_stock : LOOP
FETCH stockCursor INTO m_numofpurchaseBag,m_purchasedKg,m_purBagDtlId;
IF cursor_finish = 1 THEN
LEAVE get_stock;
END IF;
/*SELECT m_numofpurchaseBag,m_purchasedKg,m_purBagDtlId; */
/* Blending bag query*/
SET #m_numberofBlndBag:=0;
SET #m_BlndKg:=0;
/* Blend bag*/
SELECT #m_numberofBlndBag:=SUM(blending_details.`number_of_blended_bag`) AS belendedBag INTO #m_numberofBlndBag
FROM blending_details
WHERE blending_details.`purchasebag_id`= m_purBagDtlId
GROUP BY
blending_details.`purchasebag_id`;
#Blend Bag
#Blend Kgs
SELECT #m_BlndKg:=SUM(blending_details.`qty_of_bag` * blending_details.`number_of_blended_bag`) AS blendkg INTO #m_BlndKg
FROM blending_details
WHERE blending_details.`purchasebag_id`= m_purBagDtlId
GROUP BY
blending_details.`purchasebag_id`;
SET #m_StockBag:=(m_numofpurchaseBag - #m_numberofBlndBag);
SET #m_StockKg:=(m_purchasedKg - #m_BlndKg);
INSERT INTO StockTable
(
purchaseBagDtlId ,
purchasedBag ,
purchasedKg ,
blendedBag ,
blendedKg ,
stockBag ,
stockKg
)VALUES(m_purBagDtlId,m_numofpurchaseBag,m_purchasedKg,#m_numberofBlndBag,#m_BlndKg,#m_StockBag,#m_StockKg);
END LOOP get_stock;
CLOSE stockCursor;
SELECT * FROM StockTable;
#DROP TABLE StockTable;
END$$
DELIMITER ;
#CALL sp_Stock();
Anywhere I am using a temp table I am executing this before the temp table is created:
$this->db->query('DROP TABLE IF EXISTS StockTable');
I seem to remember reading someone having the same problem as you and for some reason you have to execute the above first.
So try:
$data=array();
$call_procedure = "CALL sp_Stock()";
$this->db->query('DROP TABLE IF EXISTS StockTable');
$query = $this->db->query($call_procedure);
$sql="SELECT * FROM StockTable";
$query1 = $this->db->query($sql);

Stored Procedures Return Mysql Php

I wrote a stored procedure in mysql, which does an insert into a table and the selects a field(id), so that it later be assigned to a php variable, to eventually pass it as a parameter to another mysql procedure. The first procedure works fine when I call it from mysql, it returns the value it was meant to. The problem lays on when I try to obtain that value from php.
Heres my code:
DELIMITER $
CREATE PROCEDURE addEntity(p_idPerson INT(11),
p_nameP VARCHAR(50), p_objective VARCHAR(8),
OUT p_idProduct INT(11)
)
BEGIN
INSERT INTO EntityTb (idPerson, nameP, objective) VALUES(p_idPerson, p_nameP, p_objective);
SET p_idProduct= (SELECT idProduct FROM EntityTb WHERE idPerson= p_idPerson ORDER BY idProduct DESC LIMIT 1);
SELECT p_idProduct;
END$
DELIMITER;
PHP
$prep_stmt = "CALL addEntity(?,?,?,?)";
$insert_stmt = $mysqli->prepare($prep_stmt);
$p_id= "#p_idProduct";
if ($insert_stmt) {
$insert_stmt->bind_param('issi', $arg1, $arg2, $arg3 $p_id);
$insert_stmt->execute();
while ($rs= $insert_stmt->fetch()) {
//debug($rs);
echo "\r\n rs: ".$rs;
}
}
I fixed it. Just had to change the php code above to the one below.
$insert_stmt= $mysqli->query("CALL addProduct($arg1, '$arg2', '$arg3', #p_idProduct)");
if ($insert_stmt->field_count)
{
$rs= $insert_stmt->fetch_assoc();
$id_prod= $rs['p_idProduct'];
echo "id_product: ".$id_product;
}

error getting data procedure in codeigniter

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;
}

Getting into stored procedures, need help converting a query

I never used stored procedures, but I faced a reality when I need to move my query to server. Please assist.
This is my function that I created via PHP:
function getResults($userid) {
$query = "select * from myTable where iduser= ?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $userid, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
I never used stored procedures and not sure how to approach:
How do I add this as stored procedure to MySQL, so I could submit
one integer variable to it
How do I `prepare' the integer variable that I will submit to stored procedure
How do I retrieve the result set from stored procedure back to php
function.
If you could assist, I will review your solution and will be able to continue on my own.
I checked google and I see that to create a stored procedure I need to start like this:
CREATE PROCEDURE `getResults` (IN userid INT)
BEGIN
END
MYSQL:
DELIMITER $$
DROP PROCEDURE IF EXISTS getResults$$
CREATE PROCEDURE getResults(IN I_USERID INT(10))
BEGIN
SELECT * FROM `myTable` WHERE iduser = I_USERID;
END$$
DELIMITER ;
PHP:
$sql = "CALL getResults(?)";
$stmt = $this->openDb()->prepare($sql);
$stmt->execute(array($userid));
while ($row = $stmt->fetchObject()) {
//use fields like this: $row->fieldname1, $row->fieldname2...
}
$stmt->closeCursor();
On a side note, I would recommend naming explicitely your fields instead of using the * selector in your query.
Hope it helps,
S.

Categories