I created a stored procedure like this and called that procedure with input arguments. I want to get the procedure it self while calling it with arguments just like echo query in normal case.
$procedure = "CREATE PROCEDURE pdruser_login(IN userName VARCHAR(300), IN password VARCHAR(500))
BEGIN
DECLARE _sqlQuery VARCHAR(2046);
SET _sqlQuery = 'SELECT login_id, authorized, admin_authorize FROM tbluser_login WHERE user_name = userName AND user_pwd = password AND authorized = 1 AND privacy_policy = 1 AND is_deleted = 0';
SET #sqlQuery = _sqlQuery;
PREPARE dynquery FROM #sqlQuery;
EXECUTE dynquery;
DEALLOCATE PREPARE dynquery;
END;";
if (!mysqli_query($this->con,"DROP PROCEDURE IF EXISTS pdruser_login") ||!mysqli_query($this->con,$procedure))
{
file_put_contents("minefile1.txt", "Stored procedure creation failed: (" . mysqli_errno($this->con) . ") " . mysqli_error($this->con));
}
if (!($result = mysqli_query($this->con,"CALL pdruser_login('".$userName."','".$password."'")))
{
file_put_contents("minefile2.txt","CALL failed: (" . mysqli_errno($this->con) . ") " . mysqli_error($this->con));
}
But the above procedure shows an error "CALL failed: (1064) 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 '' at line 1".
How can I display the stored procedure query while calling the stored procedure.Is there is any way for getting the dynamic query so it will be easy to trace the errors in complex queries?
For some reason you don't store your SQL in a variable - so, you cannot have it in your debug info
$sql = "DROP PROCEDURE IF EXISTS pdruser_login";
mysqli_query($this->con,$sql) or trigger_error(mysqli_error($this->con)." [$sql]");
$sql = $procedure;
mysqli_query($this->con,$sql) or trigger_error(mysqli_error($this->con)." [$sql]");
// and so on.
note that trigger_error is a way more useful that file_put_contents. it can put the error in a log file but also it can display it on-screen which id very handy. And it have indispensable file/line stamp
First for creating a MySQL procedure you need to set DELIMITER other than ; then reset delimiter after procedure execution as Inside priocedure all bock should treat as single query but query inside procedure can break sql statement (due to using ;)
Example from mysql site.
DELIMITER //
DROP PROCEDURE IF EXISTS GetAllProducts //
CREATE PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END //
DELIMITER ;
Related
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 been stumped with this and cannot find a working example or tutorial anywhere.
Given the following stored procedure:
SQL
delimiter $$
CREATE PROCECURE sp1(IN 'myoffset' INT, IN 'myrows'
INT)
begin
select * from t1
limit 'myoffset', 'myrows'
END$$
delimiter
I am trying to call it from PHP like so:
... establish $conn, then
PHP
// ver1:
$sql = ( "SET #p0 = $tmp1;" . " SET #p1 = $tmp2;" . "
CALL `sp1`(#p0, #p1);" );
//OR
//ver2
$sql = "SET #p0 = `$tmp1`; SET #p1 = `$tmp2`; CALL
`sp1`(#p0, #p1);";
$result = mysqli_query($conn, $sql);
Neither one works. MariaDB complains that
"Error description: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SET #p1 = 25; CALL sp1(#p0, #p1)' at line 2"
Any help would be much appreciated!
What is in $tmp1?
If it is a number, then the first one should work, but the second one does not make sense because it becomes
SET #p0 = `1234`;
I assume there is not a column or table named 1234? Keep in mind that backtics are for columns, tables, and database names.
If $tmp is the string "a string", then you get
SET #p0 = a string; -- strings need to be quoted here
or
SET #p0 = `a string`; -- again that is treated as a column (etc) name.
After that, you have another problem: Do not tack multiple statements together (separated by ;); run them separately.
Finally, there is no need for #p0, etc:
$sql = "CALL `sp1`('$tmp1', '$tmp2')";
is sufficient.
Well, not quite. If the values for $tmps came from the outside world, see the dreaded "SQL Injection" problem.
Oh, and what if
$tmp1 = "Don't do this";
Then you get
$sql = "CALL `sp1`('Don't do this', '$tmp2')";
Look at the single quotes. There are 3 of them. How will this be parsed?
I'm trying to call a stored procedure (SP) from my codeigniter code but one of the parameters I defined in the Mysql SP is a OUTPUT parameter which is giving me some issues when calling the SP. Does anyone know the correct way to call the Sp from the PHP code with a OUTPUT parameter involved. The code is below:
MySql:
DROP PROCEDURE IF EXISTS usp_check_user_exist;
DELIMITER $$
CREATE PROCEDURE usp_check_user_exist
( IN email VARCHAR(200),
OUT result BIT(1) )
BEGIN
SET result = EXISTS(SELECT 1 FROM tbl_users WHERE user_email = email
LIMIT 1);
SELECT result;
END
Codeigniter/php:
public function check_email($email) {
$data = array(
'email' => $email,
'#result' => #result
);
$sp = "CALL usp_check_user_exist (?,?)";
$result = $this->db->query($sp, $data);
if($result) {
return TRUE;
} else {
return FALSE;
}
}
The error I got:
You have error in your stored procedure. Please check correct defination described below.
DELIMITER $$
DROP PROCEDURE `usp_check_user_exist`$$
CREATE PROCEDURE `usp_check_user_exist`(IN email VARCHAR(200))
BEGIN
DECLARE result TINYINT DEFAULT 0;
SET result = EXISTS(SELECT 1 FROM tbl_users WHERE user_email = email 1);
SELECT result;
END$$
DELIMITER ;
Also if you want to user your current Stored Procedure than while calling from PHP use statement like describe below.
call usp_check_user_exist('example#domain.com',#out);
Let me know if it not works.
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.
The table[file_request ] structure:
user_id[INT] file_id[CHAR(10)] all_files
This is the SQL code which work fine in MySQL clien: I am using heidisql
DROP PROCEDURE IF EXISTS check_user_files;
DELIMITER \\
CREATE PROCEDURE check_user_files(IN p_user_id INT,IN p_file_id CHAR(10),IN p_all_files VARCHAR(500))
BEGIN
IF EXISTS(SELECT 1 FROM file_request WHERE user_id = p_user_id AND movie_id = p_file_id) THEN
UPDATE file_request SET `requring_date`=NOW(),`all_files`= p_all_files WHERE `user_id`=p_user_id AND `movie_id`=p_file_id;
ELSE
INSERT INTO file_request (`user_id`,`requring_date`,`movie_id`,`all_files`)
VALUES (p_user_id,NOW(),p_file_id,p_all_files);
END IF;
END \\
DELIMITER ;
CALL check_user_files('23','T40431284','07 08 10 11 13 14');
DELIMITER ;
CALL check_user_files('23','F87951','01 02 03');
And I trying to create and execute the SQL query from PHP [didn't work] :
// create the call procedure statements
foreach($fileData as $key=>$value){
$callSP .= "DELIMITER ; \n
CALL check_user_files('$userID','$key','$value');\n";
}
$insert_file_request_query = "DROP PROCEDURE IF EXISTS check_user_files;
DELIMITER \\\\
CREATE PROCEDURE check_user_files(IN p_user_id INT,IN p_file_id CHAR(10),IN p_all_files VARCHAR(500))
BEGIN
IF EXISTS(SELECT 1 FROM file_request WHERE user_id = p_user_id AND movie_id = p_file_id) THEN
UPDATE file_request SET `requring_date`=NOW(),`all_files`= p_all_files WHERE `user_id`=p_user_id AND `movie_id`=p_file_id;
ELSE
INSERT INTO file_request (`user_id`,`requring_date`,`movie_id`,`all_files`)
VALUES (p_user_id,NOW(),p_file_id,p_all_files);
END IF;
END \\\\
$callSP";
mysqli_query($conn,$insert_file_request_query);
The SQL query which created from PHP didn't work as in the MySQL client!?
So, how can I fix it!?
[update1]
I found that the SQL query must in the special format [ the formate which work fine in the MySQL client] or shouldn't work,I tried to copy and paste the query which echo from the PHP, the query code become one line and couldn't execute in MySQL client,too.
[update2]
The code of create store procedure will work fine when I execute it alone from PHP.I mean,I split the whole process into three parts and execute them one by one.
part1: drop the procedure if it was exists; [using mysqli_query()]
part2: create the procedure;[using mysqli_query()]
part3:call the procedure;[using mysqli_multi_query()]
$insert_file_request_query = '';
foreach($fileData as $key=>$value){
$insert_file_request_query .= "CALL check_save_file_request('$userID','$key','$value');";
}
mysqli_multi_query($conn,$insert_file_request_query);
And my final solution was to create the Store Procedure in MySQL and call it from the PHP.It works fine now.
Thank you very much!!
You can't combine multiple statements in mysqli_query. Split out the definition of the stored procedure from the CALLs to it. If that still fails, we'll need the full and exact error message that you receive.