Is it possible to set the result from a prepared statement into a variable? I am trying to create the following stored procedure but it is failing:
ERROR 1064 (42000) at line 31: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'stmt USING @m, @c, @a;
DROP PROCEDURE IF EXISTS deleteAction;
DELIMITER $$
CREATE PROCEDURE deleteAction(
IN modul CHAR(64),
IN controller CHAR(64),
IN actn CHAR(64))
MODIFIES SQL DATA
BEGIN
PREPARE stmt FROM 'SELECT id
FROM actions
WHERE `module` = ?
AND `controller` = ?
AND `action` = ?';
SET @m = modul;
SET @c = controller;
SET @a = actn;
SET @i = EXECUTE stmt USING @m, @c, @a;
DEALLOCATE PREPARE stmt;
DELETE FROM acl WHERE action_id = @i;
DELETE FROM actions WHERE id = @i;
END
$$
DELIMITER ;
You must always use prepared statements for any SQL query that would contain a PHP variable. To do so, always follow the below steps: Create a correct SQL SELECT statement.
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency. Prepared statements basically work like this: Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?").
MySQL prepared statement usage EXECUTE – execute a prepared statement prepared by the PREPARE statement. DEALLOCATE PREPARE – release a prepared statement.
It may seem strange, but you can assign the variable directly in the prepared statement string:
PREPARE stmt FROM 'SELECT @i := id FROM ...';
-- ...
EXECUTE stmt USING @m, @c, @a;
-- @i will hold the id returned from your query.
Test case:
CREATE TABLE actions (id int, a int);
INSERT INTO actions VALUES (1, 100);
INSERT INTO actions VALUES (2, 200);
INSERT INTO actions VALUES (3, 300);
INSERT INTO actions VALUES (4, 400);
INSERT INTO actions VALUES (5, 500);
DELIMITER $$
CREATE PROCEDURE myProc(
IN p int
)
MODIFIES SQL DATA
BEGIN
PREPARE stmt FROM 'SELECT @i := id FROM actions WHERE `a` = ?';
SET @a = p;
EXECUTE stmt USING @a;
SELECT @i AS result;
DEALLOCATE PREPARE stmt;
END
$$
DELIMITER ;
Result:
CALL myProc(400);
+---------+
| result |
+---------+
| 4 |
+---------+
1 row in set (0.00 sec)
Use this code
PREPARE stmt FROM 'SELECT ''a'' into @i' ;
EXECUTE stmt;
if(@i='a') then
............
end if;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With