Stored Procedures Return Mysql Php - 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;
}

Related

Don't know how to get values from stored procedure

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 ;

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.

Call Stored Procedure to Update table with Parameters PHP MySQL

Calling SELECT Statements with parameters is great and makes life coding so tidy. My problem comes to when I want to update data in the database using an UPDATE statement.
I have the Stored Proc with the UPDATE statement included, similar to this below
CREATE DEFINER = 'myuser'#'%'
PROCEDURE sp_upd_planning (
IN prop_id int(11),
IN planned_date varchar(15),
IN time_slot int(11),
IN by_who int(11),
IN cost decimal(15,2),
IN complete_date varchar(15),
IN lastupd_user varchar(100))
BEGIN
UPDATE planning
SET
Status = CASE
WHEN CompleteDate IS NOT NULL THEN 4
WHEN PlannedDate IS NULL THEN 2
WHEN PlannedDate IS NULL AND CompleteDate IS NULL THEN 3
END
,PlannedDate = planned_date
,BookingDate = NOW()
,TimeSlot = time_slot
,ByWho = by_who
,Cost = epc_cost
,Complete = CASE WHEN CompleteDate IS NOT NULL THEN 1 ELSE 0 END
,CompleteDate = complete_date
,LastUpdateDate = NOW()
,LastUpdateUser = lastupd_user
WHERE PropID = prop_id;
END
The statement works as should when I run the CALL sp_upd_planning(paramters here); within the database.
I'm using as a submit from a form, I've posted the relevant fields into variables and in my connection I call the Stored Proc again and as before in the database I use the variables to match the parameters needed like this (yes I know it's using mysql_ but I wanted to test quickly so I used this)
mysql_query("CALL sp_upd_planning('$planned', '$timeslot', '$bywho', '$cost', '$completed', '$inputby', $propid)") or die(mysql_error());
When the code executes all looks good and no errors and the main form submits as should with the jquery I set up, but when I check the database nothing is updated.
Why would this be?
It sounds like you aren't executing your statement. In PHP you still have to execute the statement after creation. Also if I remember correctly it is more secure to bind your parameters instead of pass them in the string. Try something like this:
$conn = new mysqli("mysql:host=$host;dbname=$dbname", $username, $password);
// execute the stored procedure
$sql = "CALL sp_upd_planning(:planned, :timeslot, :bywho, :cost, :completed, :inputby, :propid)";
$stmt = $conn->prepare($sql);
$stmt->bindParam('datatypes', $planned, $timeslot, $bywho, $cost, $completed, $inputby, $propid);
$stmt->execute();
Basically by the term datatypes lets assume the planned is a string, timeslot is a date/time, bywho is a string, cost is an int, completed is an int, inputby is a string, and propid is an int then it would say 'sdsiisi'

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.

Codeigniter - SQL Server 2008 : How to get parameter output in Store Procedure

I’ve a procedure in SQL Server 2008
CREATE PROCEDURE dbo.testing
#parm varchar(10),
#parmOUT varchar(30) OUTPUT
AS
BEGIN
SELECT #parmOUT = 'parm 1 ' + #parm
END
and i have a query to access this procedure in Codeigniter frameword.
i use sqlsrv_driver database.
$param1 = 'test';
$param2 = '1';
$this->db->query("dbo.testing ?, ?", array($param1, $param2));
i’ve execute the procedure, but i can’t retrieve 2nd parameter value ($param2).
Anyone have idea to get this 2nd parameter value??
thanks b4
In your Stored Procedure ,you are passing one input parameter and the specifying one output parameter . So the SP should be modified like the one below
ALTER PROCEDURE dbo.testing
#parm varchar(10),
#parmOUT varchar(30) OUTPUT
AS
BEGIN
SELECT 'parm 1 ' + #parm
END
Now in order to execute the above SP you need to pass just one input parameter
declare #out varchar(30)
exec testing 'test', #parmOUT=#out OUTPUT
You will just retrieve the result as
param1test
There is no second parameter which you can retrieve from your SP .The only value which you will get is the one which you have specified in your select query .
$sql = 'DECLARE #RETURNV VARCHAR(20)
EXEC dbo.testing ?, #parmOUT= #RETURNV OUTPUT
SELECT #RETURNV AS RETURNV';
$param = array(
"This is first param"
);
$temp = $this->db->query($sql, $param);
$result = $temp->result_array();
echo "<pre>".print_r($result, true)."</pre>";

Categories