I am new to stored procedures, and i am having an issue with the results returned by the stored procedure not having any values when i call the stored procedure via PHP. When i manually make the call directly on the MySQL server it works fine and returns 5 values. When i call the procedure through php no values are stored in the binding variables.
Stored Procedure:
DELIMITER $$
CREATE PROCEDURE `TPE_GET_current_repair` (IN current_repair_vid VARCHAR(45))
BEGIN
SELECT current_repair_vid v1;
SELECT
sys_vendor.vendor,
receive_date,
tape_repair_problem_code.tape_repair_problem_reason,
sys_tape_type.tape_type,
sys_capture_location.capture_location
FROM tape_repair
INNER JOIN `sys_vendor` on tape_repair.vendor_id = sys_vendor.id
INNER JOIN `tape_repair_problem_code` on tape_repair.problem_code = tape_repair_problem_code.id
INNER JOIN `sys_tape_type` on tape_repair.tape_type_id = sys_tape_type.id
INNER JOIN `sys_capture_location` on tape_repair.capture_location_id = sys_capture_location.id
WHERE vid = current_repair_vid;
END
PHP:
$repairData = "CALL TPE_GET_current_repair('$vid')";
if ($stmt = $mysqli->prepare($repairData)) {
$stmt->execute();
$stmt->bind_result($rpr_vendor, $rpr_rcv_date, $rpr_problem, $rpr_tape_type, $rpr_capt_loctn);
$stmt->fetch();
}
I fixed the issue, i had forgotten about the first select statement and it was causing the statement to fail.
Related
This question already has answers here:
PHP: Calling MySQL Stored Procedure with Both INPUT AND OUTPUT Parameters (NOT "INOUT")
(2 answers)
Closed 3 years ago.
To call a Stored procedure with an IN parameter is easy like
CREATE PROCEDURE `catalog_delete_product`(IN `inProductId` INT) BEGIN DELETE FROM product_attribute WHERE product_id = inProductId; DELETE FROM product_category WHERE product_id = inProductId; DELETE FROM shopping_cart WHERE product_id = inProductId; DELETE FROM product WHERE product_id = inProductId; END
You can see that it is as easy as that. But how do we call an OUT parameter in MySQL Stored parameter and use it in PHP?
As an example to illustrate it, I will a real world practical example(inserting data into an order table and returning the lastInsertId).
CREATE PROCEDURE `shopping_cart_create_order`(IN `inCartId` INT(11), OUT `newOrderId` INT(11)) BEGIN
DECLARE newOrder int;
-- Insert a new record into orders and obtain the new order ID
INSERT INTO orders (created_on) VALUES (NOW());
-- Obtain the new Order ID
SELECT LAST_INSERT_ID() INTO newOrder;
SET newOrder = newOrderId;
END
At PHP level// Probably at the Model/Entity level First, we need to execute the
shopping_cart_create_order()
stored procedure. Which might probably be in a function.
Second, to get the last order id, we need to query it from the variable
#oid
. It is important that we must call the method
closeCursor()
of the PDOStatement object in order to execute the next SQL statement.
function query($pdo, $sql, $parameters = []){
$query = $pdo->prepare($sql);
$query->execute($parameters);
return $query;
}
function create_order($pdo, $cart_id){
// Binding the parameters
$parameters = [':cart_id' => $cart_id];
// calling stored procedure command
$sql = 'CALL shopping_cart_create_order(:cart_id)';
// prepare for execution of the stored procedure, pass value to the command
and execute the Stored Procedure
$query = query($pdo, $sql, $parameters);
// Then close Cursor. It is important for you to close it.
$query->closeCursor();
// execute the second query to get last insert id
$row = $pdo->query("SELECT #oid AS oid")->fetch();
return $row;
}
I have a products table stored inside the database which contains info related to the product.I have a stored procedure that gets the rows with maximum quantity.
Whenever i try to call that stored procedure from the php it returns false while when i run the same query in mysql console, it returns me the rows.
PHP Code:
$resVal=$mysqli->query('CALL get_max_quant_rows("'.$company.'","'.$type.'","'.$limit.'")');
$countVal=$resVal->fetch_row();
$countVal=$countVal[0];
$results = $mysqli->query('CALL get_max_quant_rows("'.$company.'","'.$type.'","'.$limit.'")');
var_dump('CALL get_max_quant_rows("'.$company.'","'.$type.'","'.$limit.'")');
var_dump($results);
The ouput of the var_dump of the above queries give me:
string(72) "CALL get_max_quant_rows("1471941595186287666657bc0bdb1c25d","Cakes","1")" bool(false)
I have shown you the var_dump of the query as to show you that the values are going perfectly inside the stored procedure.
When i ran the same query inside the console,it ran and it gave me the results.What could pe the possible reason for this behaviour?
Stored Procedure:
DELIMITER $$
USE `dboxyz`$$
DROP PROCEDURE IF EXISTS `get_max_quant_rows`$$
CREATE PROCEDURE `get_max_quant_rows`(company VARCHAR(8000),product_type VARCHAR(8000),limiter INT)
BEGIN
DECLARE emptyCheckFirst BIT;
DECLARE emptyCheckSecond BIT;
SET emptyCheckFirst=`dboxyz`.isNullOrEmpty(company);
SET emptyCheckSecond=`dboxyz`.isNullOrEmpty(product_type);
IF (emptyCheckFirst=0 AND emptyCheckSecond=0)
THEN
SELECT p1.id,p1.price,p1.product_code,p1.product_name,p1.quantity,p1.amount,p1.companyId FROM products p1
INNER JOIN (SELECT product_code,MAX(quantity) max_quantity FROM products WHERE companyId=company AND `type`=product_type
GROUP BY product_code) p2 ON p1.product_code=p2.product_code AND p1.quantity=p2.max_quantity LIMIT limiter;
END IF;
IF emptyCheckFirst=1 AND emptyCheckSecond=1
THEN
SELECT p1.id,p1.price,p1.product_code,p1.product_name,p1.quantity,p1.amount,p1.companyId FROM products p1
INNER JOIN (SELECT product_code,MAX(quantity) max_quantity FROM products
GROUP BY product_code) p2 ON p1.product_code=p2.product_code AND p1.quantity=p2.max_quantity LIMIT limiter;
END IF;
END$$
DELIMITER ;
Update:
Error given by the DB
Commands out of sync; you can't run this command now
DELIMITER $$
USE `dboxyz`$$
DROP FUNCTION IF EXISTS `isNullOrEmpty`$$
CREATE FUNCTION `isNullOrEmpty`(xx VARCHAR(8000)) RETURNS BIT(1)
BEGIN
DECLARE somevariable VARCHAR(8000);
SET somevariable=xx;
IF (somevariable IS NOT NULL AND LEN(somevariable)>0)
THEN
RETURN 0;
ELSE
RETURN 1;
END IF;
END$$
DELIMITER ;
MySQL stored procedures can return more than one result set, that is the reason to clear all results before do another query using the same connection.
Just use next_result, and do another query:
$results = $mysqli->query("CALL stored_procedure()");
$mysqli->next_result();
$results2 = $mysqli->query("CALL another_stored_procedure()");
I am currently trying to execute a stored procedure(Two INSERTS and a SELECT) through PHP. The stored procedure works (no errors are thrown). The values are even inserted into the given tables. We are storing the result in a JSON object but it is returning an empty array. When we execute the stored procedure containing only a SELECT it returns the correct values. All the names have been changed in our tables (may have missed some but our code runs). Can anyone shed light on why our array is not populating?
Here is our stored procedure
ALTER procedure
As
BEGIN
INSERT INTO TABLE1
(Loan_ID, Doc_ID, Borrower_Name, Docs_Drawn, Funder, First_Payment, Interest_Rate, Loan_Amount)
Select Loan_ID,
(SELECT (COUNT(*)) FROM TABLE WHERE A.Loan_ID = Loan_ID) AS Doc_ID,
Borrower ,[Date_Docs_Drawn]
,[Funder]
,[Payment_Date]
,[Interest_Rate]
,[Loan_Amount] from VIEW A
INSERT INTO TABLE2
(Loan_ID, Submitted_By, Event_Class, Event_Type, Event_Date, Doc_ID)
SELECT A.[Loan_ID],
'Program' AS Submitted_By
,'Collateral' AS Event_Class
, 'Outstanding' AS Event_Type
, CURRENT_TIMESTAMP AS Event_Date
, Doc_ID
FROM TABLE1 AS A
WHERE NOT (A.Loan_ID = ANY (SELECT Loan_ID FROM TABLE2))
SELECT [Loan_ID],[Doc_ID],[Borrower_Name]
,[Funder]
,[Docs_Drawn]
,[First_Payment]
,[Loan_Amount]
,[Interest_Rate]
FROM TABLE1
WHERE Loan_ID <> ALL
(SELECT Loan_ID FROM TABLE2
WHERE Event_Type <> 'Outstanding')
ORDER BY Funder
END
here is a rough sketch of our PHP
$query = "exec storedProcedure";
$result=sqlsrv_query($conn, $query);
$table = array();
while($row = sqlsrv_fetch_array($result)) {
$table[] = $row;
}
echo json_encode($table);
Try using SET NOCOUNT ON in your stored procedure. You are probably being limited by the results returned to the PHP from the SQL Server PHP driver, so you aren't getting the data from the SELECT statement.
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.
I am having difficulty figuring out how to add data as input to an Oracle cursor being sent to a stored procedure of a package in PHP.
I am trying to send 2 pieces of data through a cursor. I have verified the data is correct up to sending.
PHP Code:
$finalpieces = explode('|',$lkeyarr[$i]); //0=unique id, 1=table
$conn = oci_connect($oracleUsername,$oraclePassword,$oracleService);
$stmt = OCIParse($conn,"BEGIN PROD.PKG_CORE_OBSERVER.StuckPages_Unlock(:cur_PageDetails); END;");
$cur = oci_new_cursor($conn);
OCIBindByName($stmt,':cur_PageDetails',$cur,-1,OCI_B_CURSOR);
ociexecute($stmt,OCI_DEFAULT);
Stored Procedure Details:
PROCEDURE StuckPages_Unlock
(
cur_PageDetails IN OUT SYS_REFCURSOR
)
accepts ref cursor that includes 2 fields:
ProcessID NUMBER(2);
PageUniqueID NUMBER(10);
Any help would be greatly appreciated.
A Ref Cursor is a pointer to a result set. We cannot assign values to a Ref Cursor, we use it with a query:
open my_ref_cursor for
select process_id, page_unique_id
from some_table;
So, your approach is wrong. It is difficult to be sure what you're trying to achieve but I think what you want is a stored procedure which accepts two parameters that it uses to query a table and return a ref cursor. Perhaps, something like this:
PROCEDURE StuckPages_Unlock
(
p_proc_id in some_table.process_id%type
, p_page_id in some_table.page_unique_id_id%type
, cur_PageDetails OUT SYS_REFCURSOR
)
IS
open PageDetails for
select *
from some_table
where process_id = p_proc_id
and page_unique_id = p_page_id;
END;