concatenation in stored procedure mysql - php

I want to create concatenation for store procedure mysql.
in php I can use (.) for concatinating the variable
example :
$table = "table_".$_GET["number"];
$sql = mysqli_query($conn,select * from `".$table."` where `field`='$field');
in stored procedure mysql, I don't know how to concatinate the variable.
this is my stored procedure script.
CREATE DEFINER=`user`#`localhost` PROCEDURE `testprocedure`(v_number int(5))
BEGIN
declare v_table varchar(20);
set v_table = 'table_'.v_number;
update `v_table` set `field`=v_number where `field2`='test';
END $$
DELIMITER ;
so how can I add v_number to set v_table then add v_table to update table query?

Use CONCAT : set v_table = CONCAT('table_',v_number);

Related

How to retrieve data using primary key (INT) by store Procedure in sql?

I've created a store procedure to fetch data. The sql code is below. when i'm using another column(varchar) its working .. but when i'm trying to use by primary key (int) the below code is not working.
Create PROCEDURE ABC
(in #ID int)
as
Begin
SELECT *
FROM class
where id = #ID
END
DECLARE #ID INT;
SET #ID = 26;
CALL ABC(#ID)
This is database
Lots if mistakes here try
drop procedure if exists p;
delimiter $$
Create PROCEDURE p
(in inID int)
Begin
SELECT *
FROM users
where id = inID;
END $$
delimiter ;
SET #ID = 1;
CALL p(#ID)

Call count result from stored procedure MySQL in PHP

I'm trying to get a value from a stored procedure in php but I can't do it.
My stored procedure:
DROP PROCEDURE IF EXISTS sp_table;
DELIMITER $$
CREATE PROCEDURE sp_table()
BEGIN
SELECT COUNT(*) FROM table;
END$$
DELIMITER ;
My PHP code:
$recordSet_table = $conn->query("CALL sp_table()");
print_r($recordSet_table)."<br><br>";
Please try following code.
$sql = mysqli_query($connectionVariable,"CALL sp_table(#count)");
$result = mysqli_fetch_array($sql);

how to update multiple columns from a trigger MySQL

hi i am using mysql trigger to update a table on another table's insertion
this trigger works fine
CREATE TRIGGER `update_pupil_subject` AFTER INSERT ON `pupil_marks`
FOR EACH ROW
BEGIN
UPDATE pupil_subjects SET NumberOfStudens = NumberOfStudens + 1 WHERE NEW.SubjectID = SubjectID;
END$$
but this gives an error
CREATE TRIGGER `update_pupil_subject` AFTER INSERT ON `pupil_marks`
FOR EACH ROW
BEGIN
UPDATE pupil_subjects SET NumberOfStudens = NumberOfStudens + 1 , AverageMarks = (SELECT AVG(Marks) FROM pupil_marks WHERE NEW.StudentID = StudentID ) WHERE NEW.SubjectID = SubjectID;
END$$
how to write this correctly , please help . thanks in advance .
Apparently there were problems when sub-queries were used:
Can you try splitting the SQL statement:
DELIMITER $$
CREATE TRIGGER `update_pupil_subject`
AFTER INSERT
ON `pupil_marks`
FOR EACH ROW
BEGIN
DECLARE avg_marks float;
SELECT AVG(Marks)
INTO avg_marks
FROM pupil_marks
WHERE NEW.SubjectID = SubjectID;
UPDATE pupil_subjects
SET NumberOfStudens = NumberOfStudens + 1, AverageMarks = avg_marks
WHERE NEW.SubjectID = SubjectID;
END
$$
Edit: Use
SHOW TRIGGERS WHERE `table` = 'pupil_marks';
to get all triggers defined on pupil_marks. You can't have multiple triggers on an event as all actions can be covered in single trigger.
NOTE: I think AVG(Marks) is for a given subject, so modified trigger definition accordingly.
declare a variable inside the trigger and assign it with the subquery
declare avg_mark integer default 0;
set avg_mark := (SELECT AVG(Marks) FROM pupil_marks WHERE NEW.StudentID = StudentID);
then use the variable "avg_mark" in your update statement...
it may work...
if not then check the delimiter just below phpmyadmin sql box . It should be "$$"

Get Updated Value in MySQL instead of affected rows

I've been trying to find an answer to this question, but haven't found any definitive "yes" or "no" in all my research.
I'm running a simple MySQL query like this:
UPDATE item SET `score`=`score`+1 WHERE `id`=1
Is there a way for that query to return the updated value, instead of the number of rows affected? Just as a reference, I'm doing this in PHP, so the actual code looks like:
$sql = "UPDATE item SET `score`=`score`+1 WHERE `id`=1";
$new_value = mysql_query($sql);
//Unfortunately this does not return the new value
I know I could do a second query and just SELECT the value, but I'm trying to cut down on queries as much as possible. Is there a way?
You can do it with a stored procedure that updates, and then selects the new value into an output parameter.
The following returns one column new_score with the new value.
DELIMITER $$ -- Change DELIMITER in order to use ; withn the procedure
CREATE PROCEDURE increment_score
(
IN id_in INT
)
BEGIN
UPDATE item SET score = score + 1 WHERE id = id_in;
SELECT score AS new_score FROM item WHERE id = id_in;
END
$$ -- Finish CREATE PROCEDURE statement
DELIMITER ; -- Reset DELIMITER to standard ;
In PHP:
$result = mysql_query("CALL increment_score($id)");
$row = mysql_fetch_array($result);
echo $row['new_score'];
No, there's nothing like postgresql's UPDATE ... RETURNING output_expression in MySQL (yet?).
If you don't want to run another Query SELECT then here is another way to do it. I have modified Mr. Berkowski code for reference:
DELIMITER $$
CREATE PROCEDURE increment_score
(
IN id_in INT
)
BEGIN
set #newScore := null;
UPDATE item SET score = IF((#newScore := score+1) <> NULL IS NULL, #newScore, NULL) WHERE id = id_in;
SELECT #newScore;
END
DELIMITER ;
No you cant. You could make a function or stored procedure that could do the insert and return the updated value but that would still require you to execute two queries from within the function or stored procedure.
You can create a trigger, and you will know everything about the modifications.

Pass mysql query containing mysql function to PHP mysql_query

I have this code
DELIMITER $$
DROP FUNCTION IF EXISTS `GetNextID` $$
CREATE FUNCTION `GetNextID`() RETURNS INT DETERMINISTIC
BEGIN
DECLARE NextID INT;
SELECT MAX(articleID) + 5 INTO NextID FROM table_article;
RETURN NextID;
END$$
DELIMITER ;
INSERT INTO table_article ( articleID, articleAlias ) VALUES ( GetNextID(), 'TEST' );
executed OK in phpMyAdmin, but it fails when i pass this query to mysql_query PHP function/
Me guess this is because of the function and semi-colons. What do i do?
DELIMITER is not a MySQL keyword: it is a reserved word parsed by clients (like mysql, phpMyAdmin etc.) which allows splitting the queries.
You should split it manually and submit the three queries:
DROP FUNCTION IF EXISTS `GetNextID`
,
CREATE FUNCTION `GetNextID`() RETURNS INT DETERMINISTIC
BEGIN
DECLARE NextID INT;
SELECT MAX(articleID) + 5 INTO NextID FROM table_article;
RETURN NextID;
END
and
INSERT INTO table_article ( articleID, articleAlias ) VALUES ( GetNextID(), 'TEST' )
in three separate calls to the database.
you have DECLARE NextID INT; and RETURN NextID; and another line with ; inside the DELIMITER $$ deceleration.
my advice is stop using $$ as a delimiter

Categories