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.
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;
}
how i can get output value from stored procedure to php variable ..
example Stored procedure :
DROP PROCEDURE `test`; CREATE DEFINER=`mydbinstance`#`%` PROCEDURE `test`(OUT `max` INT(11)) NOT DETERMINISTIC MODIFIES SQL DATA SQL SECURITY DEFINER
BEGIN
SELECT MAX(slno)+1 INTO #max FROM table1;
SELECT #max;
END
php:
$stmt=mysqli_query($conn,"CALL test();");
You should be able to get the result(s) of a stored procedure the same way you would any other query:
$stmt = mysqli_query($conn,"CALL test();");
if ($row = mysqli_fetch_row($stmt)) {
$value = $row[0];
}
I have to insert data into tblusers for which I have writen stored routine in mysql which has following insert statement:
CREATE DEFINER=`root`#`localhost` PROCEDURE `insert_user`(IN `user_name` VARCHAR(255), IN `user_age` INT, IN `user_desgn` VARCHAR(255), OUT `return_message` VARCHAR(255))
BEGIN
INSERT INTO tblusers
VALUES (user_name,user_age,user_desgn);
SET return_message = 'Congratulations Inserted Successfully';
END
I have a form in php which is used to insert the data into the table. Once I submit the form I would like to pass the form element stored in $_POST array into my stored routine insert user.
Presently I am using php pdo to call procedures ( prepare and bind ) as following:
$stmt = $handler->prepare("CALL insert_user(?,?,?,#return_msg)");
$name = $_POST['username'];
$age = $_POST['userage'];
$desgn = $_POST['userdesgn'];
$stmt->bindParam(1, $name, PDO::PARAM_STR, 50);
$stmt->bindParam(2, $age, PDO::PARAM_INT);
$stmt->bindParam(3, $desgn, PDO::PARAM_STR, 50);
// call the stored procedure
$stmt->execute();
This is working perfectly. But when I have more number of columns, the code becomes lengthy, hence I want to change my way doing things. I want to pass $_POST array to stored routine and insert the data. Is there any way I can achieve that ? Please guide me what changes I have to do in my stored procedure and in my php pdo code respectively. I am new to php, it would be great if you can explain with an example.
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'
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.