Pass mysql query containing mysql function to PHP mysql_query - php

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

Related

Q: Get ancestors with a node in mysql

Here is the reference link that I used to create procedures: https://dba.stackexchange.com/questions/7147/find-highest-level-of-a-hierarchical-field-with-vs-without-ctes/7161#7161?newreg=88de047579d242c98b8cfe0e17f0330f
Procedures are working well with the example. But not working in my own database. Seems I do something wrong while creating procedures.
Here is the procedure for my db:
DELIMITER $$
DROP FUNCTION IF EXISTS `demo`.`GetParentIDByID` $$
CREATE FUNCTION `demo`.`GetParentIDByID` (GivenID INT) RETURNS INT
DETERMINISTIC
BEGIN
DECLARE rv INT;
SELECT IFNULL(user_by,-1) INTO rv FROM
(SELECT user_by FROM users WHERE id = GivenID) A;
RETURN rv;
END $$
DELIMITER ;
Sql query for the following procedure is working fine. It is basically getting parent_id of the node:
SELECT id,GetParentIDByID(id) FROM users;
Issue occurs when I am try to get Ancestors. Here is the Procedure that I am using:
DELIMITER $$
DROP FUNCTION IF EXISTS `demo`.`GetAncestry` $$
CREATE FUNCTION `demo`.`GetAncestry` (GivenID INT) RETURNS VARCHAR(1024)
DETERMINISTIC
BEGIN
DECLARE rv VARCHAR(1024);
DECLARE cm CHAR(1);
DECLARE ch INT;
SET rv = '';
SET cm = '';
SET ch = GivenID;
WHILE ch > 0 DO
SELECT IFNULL(user_by,-1) INTO ch FROM
(SELECT user_by FROM users WHERE id = ch) A;
IF ch > 0 THEN
SET rv = CONCAT(rv,cm,ch);
SET cm = ',';
END IF;
END WHILE;
RETURN rv;
END $$
DELIMITER ;
SQL query:
SELECT id,GetAncestry(id) FROM users;
Phpmyadmin getting stuck, if I am using this query. It never returns me anything nor an error or success

concatenation in stored procedure mysql

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);

Mysql Stored Procedure and Php

I have created this procedure:
DROP PROCEDURE IF EXISTS add_com;
DELIMITER //
CREATE PROCEDURE add_com (cd CHAR(16), n VARCHAR(20), t VARCHAR(20), i VARCHAR(20))
BEGIN
DECLARE num INT;
DECLARE msg varchar(20);
set #num=select COUNT(*) from commercianti where codice_fiscale=cd;
IF num==0 THEN
insert into commercianti values (cd,n,i,t);
set #msg="Commerciante inserito";
ELSE
insert into errors values (1);
set #msg="Commerciante presente";
END IF;
return #msg;
END; //
then in a PHP page I execute this code:
<?php
$cd=$_POST['codice_fiscale'];
$n=$_POST['nominativo'];
$t=$_POST['telefono'];
$i=$_POST['indirizzo'];
if(!$cd||!$n||!$t||!$i)
echo "No data";
else{
require dirname(__FILE__) . '/' . 'dbconfig.php';
$mysqli = new MySQLI(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$result = $mysqli->query("CALL add_com('$cd','$n','$t','$i')");
echo $result;
}
?>
But the value of $result is undefined and seems the procedure doesn't work or isn't called.
If you want to get data back from a routine, you should be using a function, rather than a procedure. They have nearly the same syntax, but most notably is the RETURNS type section of the declaration. Take a look at the official documentation:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Note that the SECOND create block there is the one regarding functions. The first deals with procedures.
So I think that would look something like this:
DROP FUNCTION IF EXISTS add_com;
DELIMITER //
CREATE FUNCTION add_com (cd CHAR(16), n VARCHAR(20), t VARCHAR(20), i VARCHAR(20))
RETURNS VARCHAR(20)
BEGIN
DECLARE num INT;
DECLARE msg varchar(20);
SELECT COUNT(*) INTO #num FROM commercianti WHERE codice_fiscale = cd;
IF num==0 THEN
insert into commercianti values (cd,n,i,t);
set #msg="Commerciante inserito";
ELSE
insert into errors values (1);
set #msg="Commerciante presente";
END IF;
return #msg;
END; //
I'm not 100% sure about the RETURNS VARCHAR(20). That might have to be simply RETURNS VARCHAR.
Try changing
IF num==0 THEN
to
IF num=0 THEN

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 "$$"

Insert query in mysql using stored procedure

I have to insert datas using stored procedure in mysql.Here is my SP and function call to that SP.But I can't insert values using them. Can you please verify and give me what to do?
SP is:
delimiter ; ;
DROP PROCEDURE IF EXISTS sp_insertUserDetails ; ;
CREATE PROCEDURE sp_insertUserDetails( )
BEGIN
INSERT INTO tbl_userDetails
( strEmail,bitAllowClicktoFBProfile,bitIsAbbreviateLastName, strAboutMe )
VALUES ($strEmail, $bitAllow, $bitAbbreviate, $strAbout);
END
Call to this SP from php file:
$query = mysql_query("CALL sp_insertUserDetails($strEmail, $bitAllow, $bitAbbreviate, $strAbout)");
You dont define any arguments to your SP - did you even try call it straight from SQL eg:
mysql> call sp_insertUserDetails("foo", "bar", "dave", "str");
ERROR 1318 (42000): Incorrect number of arguments for PROCEDURE test.sp_insertUserDetails; expected 0, got 4
You need something like this
DROP PROCEDURE IF EXISTS sp_name;
delimiter ;;
CREATE PROCEDURE sp_name(fname varchar (20), lname varchar(20))
BEGIN
SELECT concat('Hello ', fname, ',', lname);
END
;;
delimiter ;
just do this
HERE i am assuming that all values are in varchar
DELIMITER //
DROP PROCEDURE IF EXISTS sp_insertUserDetails;
CREATE PROCEDURE sp_insertUserDetails(
IN strEmail varchar(255),
IN bitAllow varchar(255),
IN bitAbbreviate varchar(255),
IN strAbout varchar(255)
)
BEGIN
INSERT INTO tbl_userDetails
( strEmail,bitAllowClicktoFBProfile,bitIsAbbreviateLastName, strAboutMe )
VALUES (strEmail, bitAllow, bitAbbreviate, strAbout);
END //
DELIMITER ;
and call like this
mysql_query( CALL sp_insertUserDetails($strEmail, $bitAllow, $bitAbbreviate, $strAbout) )

Categories