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
Related
The SQL guy wrote a stored procedure that is suppose to return a list of item that'd be affected by the request.
If I call the stored procedure within SQL Server Management Studio like the example below, I can see the list in a column named after the alias
DECLARE #RETURN_CLIENTS_SET nvarchar(max)
EXEC [dbo].[Sp_IHM_SET_FORMS_INDPROD_CLOSE_DATE]
#Date = N'20171110',
#RETURN_ITEMS = #RETURN_ITEMS OUTPUT
SELECT #RETURN_ITEMS as N'#RETURN_ITEMS'
Now, If I try to show the result via a PHP like I'd do for a simple table fetch
$query_setdata = "DECLARE #RETURN_CLIENTS_SET nvarchar(max)
EXEC [dbo].[Sp_IHM_SET_FORMS_INDPROD_CLOSE_DATE]
#Date = N'20171110',
#RETURN_ITEMS = #RETURN_ITEMS OUTPUT
SELECT #RETURN_ITEMS as N'#RETURN_ITEMS'";
$prep_setdata = sqlsrv_prepare($conn, $query_setdata);
if(sqlsrv_execute($prep_setdata))
{
while($data = sqlsrv_fetch_array($prep_setdata,SQLSRV_FETCH_ASSOC)) {
echo $data['#RETURN_ITEMS'];
}
}
else {
die(print_r( sqlsrv_errors(), true));
}
The stored procedure does its stuff in the database (changing some flags for certain items), I have no error, but it doesn't show the "RETURN_ITEMS" value
Try a batch like this:
SET NOCOUNT ON;
DECLARE #RETURN_ITEMS nvarchar(max);
EXEC [dbo].[Sp_IHM_SET_FORMS_INDPROD_CLOSE_DATE]
#Date = N'20171110',
#RETURN_ITEMS = #RETURN_ITEMS OUTPUT;
SELECT #RETURN_ITEMS as RETURN_ITEMS;
The row count messages confuse some client drivers. The resultset column name should be an ordinary identifier, and the local variable you declare needs to be the one you return. And it can have the same name as the stored proc output parameter.
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 created a stored procedure, which saves values in a table temporal.y then I show with the "select " but only in my sqlserver works well . when you call the procedure in codeigniter I generated an empty array.
THIS IS MY PROCEDURE IN CODEIGNITER
function verificacion_ocupados($codigo,$llave_maestra){
$sql = "sp_verificacionocupados ?, ?";
$query = $this->db->query($sql,array($codigo, $llave_maestra));
$data = $query->result();
$query->free_result();
return $data;
}
THIS IS MY PROCEDURE
CREATE PROCEDURE [dbo].[sp_verificacionocupados]
#codigo int,
#llave_maestro varchar(50)
AS
DECLARE #finicio date;
DECLARE #ffinal date;
DECLARE #codigo_dias int;
DECLARE #no VARCHAR(100);
create table #pivote(
code int
);
SET #no='veremos';
BEGIN
SELECT #ffinal=Oel_Fecha_Fin,#finicio=Oel_Fecha_Inicio
FROM Operaciones_Especiales_Llave
where Em_Codigo=#codigo and Oel_Estado=2 and Th_Llave=#llave_maestro ;
IF ##ROWCOUNT>0
BEGIN
INSERT INTO #pivote VALUES (2);
END
END
SELECT code from #pivote;
GO
This is just one example of a much larger consultation I am doing .
I think the problem is in the temporary table and as I call to return data.
Who has an idea what is the problem ? . Thanks in advance
change it as following.
function verificacion_ocupados($codigo,$llave_maestra)
{
$sql="sp_verificacionocupadose ?, ?";
$query=$this->db->query('call sp_verificacionocupadose("$codigo","$llave_maestra")'));
$data=$query->result();
$query->free_result();
return $data;
}
I want to do a Migration data from one table to another.
I wrote a simple PHP script for my purposes but I wanted to do this by MySql script using user defined variables:
the PHP script looks like this:
//MIGRATION
$sql = "SELECT position FROM ts_user_config WHERE position != '' AND position NOT REGEXP '^-?[0-9]+$' GROUP BY TRIM(position) ORDER BY position";
$positions = db_loadColumn( $sql );
foreach ($positions as $key => $pos) {
$sql = "SELECT id FROM user_positions where UPPER(position) = UPPER('$pos')";
$posId = db_loadResult($sql);
if ($posId == null) {
$sql = "INSERT INTO user_positions (position, `desc`) VALUES ('$pos', '$pos')";
db_exec($sql);
$posId = db_insert_id();
}
$sql = "UPDATE ts_user_config SET position='$posId' WHERE TRIM(position)='$pos'";
db_exec($sql);
}
//---------
Could somebody be so kind and rewrite this PHP instructions to MySQL script? I tried to do this but my mySQL knowledge is very low and I couldn't done that.
Please help me if its not too much effort.
Thank you in advance.
I Have DONE IT !!!!!! :)
this is my mySQL script, I dont know if its perfect but its do what I need. Please tell me if I can make something better here. Thanks again :)
drop procedure if exists PositionMigration;
delimiter '//'
CREATE PROCEDURE PositionMigration()
BEGIN
BLOCK1: BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE pos VARCHAR(100);
DECLARE posId1 INT;
DECLARE posId2 INT;
DECLARE sql1 CURSOR FOR SELECT position FROM ts_user_config WHERE position != '' AND position NOT REGEXP '^-?[0-9]+$' GROUP BY TRIM(position) ORDER BY position;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN sql1;
read_loop: LOOP
FETCH sql1 INTO pos;
IF done THEN
LEAVE read_loop;
END IF;
BLOCK2: BEGIN
DECLARE posNotFound INT DEFAULT FALSE;
DECLARE sql2 CURSOR FOR SELECT id FROM user_positions where UPPER(position) = UPPER(pos);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET posNotFound = TRUE;
OPEN sql2;
FETCH sql2 INTO posId1;
IF posNotFound THEN
INSERT INTO user_positions (position, \`desc\`) VALUES (pos, pos);
BLOCK3: BEGIN
DECLARE sql3 CURSOR FOR SELECT LAST_INSERT_ID();
OPEN sql3;
FETCH sql3 INTO posId2;
UPDATE ts_user_config SET position=posId2 WHERE TRIM(position)=pos;
CLOSE sql3;
END BLOCK3;
ELSE
UPDATE ts_user_config SET position=posId1 WHERE TRIM(position)=pos;
END IF;
CLOSE sql2;
END BLOCK2;
END LOOP;
CLOSE sql1;
END BLOCK1;
END;
//
delimiter ';'
call PositionMigration();
I have created the following stored procedure in mysql...
DELIMITER //
CREATE PROCEDURE GetMember(IN in_memberID int)
BEGIN
SELECT *
FROM Members
WHERE MemberID = in_memberID;
END//
$result = mysql_query("CALL GetMember(".$memberID.")") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row['Name'] . "</br>";
}
But when I call it from php it returns all records in the Members table, what am I doing wrong?
EDIT:
When I try to call the query within phpmyadmin I get this error
CALL GetMember(1);
#1312 - PROCEDURE myDb.GetMember can't return a result set in the given context
what version of PHP?
PHP 5.2.3 and PHP 5.2.4 have a bug with procedures:
https://bugs.php.net/bug.php?id=42548
use Database_Name;
DELIMETER $$
DROP PROCEDURE IF EXISTS Proc$$
CREATE PROCEDURE Proc()
BEGIN
DECLARE x INT;
SET x = 1;
WHILE x <= 110000 DO
INSERT INTO Table_Name (word, mean) VALUES ('a', 'a mean');
SET x = x + 1;
END WHILE;
END$$
DELIMITER ;