I am using procedure first time.How can I fetch data using procedure.I created this procedure in sql file.
CREATE PROCEDURE `GetUserProfile`(IN p_user_id INT, IN p_enabled BIT)
READS SQL DATA
BEGIN
# prepare init params
if p_user_id = 0 then
set p_user_id = null;
end if;
select parent_user_id
,user_id
,Last_name
,First_name
,email as Email_address
,mobile as Phone
from app_users
where app_user_id = IFNULL(p_user_id, user_id)
and enabled = IFNULL(p_enabled, enabled);
then How can I fetch the user detail through PHP like First_name,Last_name etc.
thanks
Do you can use sqlsrv_connect function to connect to SQL Server db, use sqlsrv_prepare function to call tsql function and $params args and, at last, use one of the sqlsrv_fetch_* function to retrieve data.
see instruction on this page:
http://technet.microsoft.com/en-us/library/cc793139(v=sql.90).aspx
You can use PDO to execute a mysql stored procedure and access the results.
See the examples on this page from the PHP Documentation. In particular example #4
<?php
$stmt = $dbh->prepare("CALL sp_returns_string(?)");
$stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000);
// call the stored procedure
$stmt->execute();
print "procedure returned $return_value\n";
?>
and example #5
<?php
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);
// call the stored procedure
$stmt->execute();
print "procedure returned $value\n";
?>
If you haven't used PDO before I'd suggest browsing through the documentation, creating a new PDO object to manipulate a dabase is as simple as:
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
Related
I have a stored procedure that when called updates few tables and eventually returns an integer value.
When I call this stored procedure using SQL Pro tool, I get back a result as expected. The SQL that is auto-generated by the tool is this;
DECLARE #return_value int
EXEC #return_value =
dbo.GetNextReference
#c_tableName = 'prp',
#c_offYear = 'rcs14'
SELECT
'Return Value' = #return_value
However, I can't seem to get the same results or any results when I try to execute this using PHP PDO driver.
This is my code so far;
$conn = $this->getPDO();
$sql = "CALL GetNextReference (? , ?)";
$stmt = $conn->prepare($sql);
$tbl = 'prp';
$year = "rcs14";
$stmt->execute([$tbl, $year]);
$results = $stmt->fetchAll();
The statement executes without any errors but the results come back as an empty array.
What am I missing?
Sorry, I can't post the actual stored procedure as I am not permitted.
If I understand your question correctly and if you want to check the result of stored procedure execution, you may try with this:
<?php
# Connection
$server = 'server\instance,port';
$database = 'database';
$uid = 'user';
$pwd = 'password';
# Statement
try {
$conn = new PDO("sqlsrv:server=$server;Database=$database", $uid, $pwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server" );
}
try {
$sql = "{? = call GetNextReference (? , ?)}";
# This should work also.
#$sql = "exec ? = GetNextReference (? , ?)";
$spresult = 0;
$tbl = 'prp';
$year = "rcs14";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $spresult, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
$stmt->bindParam(2, $tbl);
$stmt->bindParam(3, $year);
$stmt->execute();
# Next line for single resultset
#$results = $stmt->fetchAll();
# Multiple resultsets
do {
$results = $stmt->fetchAll();
print_r($results, true);
} while ($stmt->nextRowset());
} catch( PDOException $e ) {
die( "Error connecting to SQL Server" );
}
$stmt = null;
$conn = null;
echo 'Stored procedure return value : '.$spresult."</br>";
?>
Op has asked for an example of an OUTPUT parameter. it doesn't specifically answer their question, however, is far too long for a comment:
USE Sandbox;
GO
--Sample Table
CREATE TABLE dbo.TestTable (ID int IDENTITY(1,1),
SomeString varchar(20));
GO
--Sample proc
CREATE PROC dbo.TestSP #SomeString varchar(20), #ID int OUTPUT AS
--You cannot OUTPUT from an INSERT into a scalar variable, so we need a table variable
DECLARE #IDt table(ID int);
INSERT INTO dbo.TestTable (SomeString)
OUTPUT inserted.ID
INTO #IDt
SELECT #SomeString;
--Now set the scalar OUTPUT parameter to the value in the table variable
SET #ID = (SELECT ID FROM #IDt); --this works, as the SP is designed for only one row insertion
GO
DECLARE #SomeString varchar(20) = 'abc', #ID int;
EXEC dbo.TestSP #SomeString = #SomeString,
#ID = #ID OUTPUT; --ID now has the value of the IDENTITY column
--We can check here:
SELECT #ID AS OutputID;
SELECT *
FROM dbo.TestTable;
GO
--Clean up
DROP PROC dbo.TestSP;
DROP TABLE dbo.TestTable;
GO
What is wrong in this code?
$statement = $dbConn->prepare("CALL SearchUser(?)");
$statement->bindParam(1, $username, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);
This is the procedure:
CREATE PROCEDURE SearchUser(IN Username VARCHAR(10), OUT numRows INT)
BEGIN SELECT COUNT(*) INTO numRows
FROM USER
WHERE Username='IN';
END//
The error is: Incorrect number of arguments for PROCEDURE, expected 2 got 1.
Why? Thank you.
You need to pass two parameter
$statement = $dbConn->prepare("CALL SearchUser(?,?)");
$statement->bindParam(1, $username, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000);
$statement->bindParam(2, $rowcount, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
You could refer this article
I am learning the php game - and am in need of completing two tasks in one .php file. What I need is
1) Connect To Server
2) Execute Stored Procedure (runs an insert into statement)
3) When stored proc fully executes run select statement against table
4) Echo the results
This is my syntax -> and I get an error that the table tablecreatedfromproc does not exist. Is the Select statement firing before the stored proc fully executes? If I run the stored procedure manually, it executes as it should (meaning it is valid syntax) - but when I try to run it from my php file I get the error.
How should this syntax be updated so that it executes as I need it to?
//connection string
$hostname = 'hostname';
$dbname = 'dbname';
$username = 'username';
$password = 'password';
$dbh = new PDO("dblib:host=$hostname;dbname=$dbname","$username","$password");
//Parsing the passed in data
$passedparams = implode(',',$_REQUEST['passedparams']);
//Capturing the dates from passed in data
$d1 = $_REQUEST['d1'];
$d2 = $_REQUEST['d2'];
//Run Stored Procedure To Create Table
$proc = mssql_init('HoldingPattern',$conn);
mssql_bind($proc,'#d1',$d1,SQLVARCHAR);
mssql_bind($proc,'#d2',$d2,SQLVARCHAR);
//Create Query String to query newly created table
$sql = "SELECT ".$passedparams." FROM tablecreatedfromproc";
$stmt = $dbh->prepare($sql);
$stmt->execute();
you are using PDO to connect, in the same time that you are trying to execute another function mssql_* -which is removed in php7-
use PDO to execute your procedures ,
$stmt = $dbh->prepare("HoldingPattern");
$stmt->bindParam(/* your required parameters goes here */);
$stmt->execute();
as mentioned here:
If you need to get Output variable from MSSQL stored procedure, try this :
-- PROCEDURE
CREATE PROCEDURE spReturn_Int #err int OUTPUT
AS
SET #err = 11
GO
$sth = $dbh->prepare("EXECUTE spReturn_Int ?");
$sth->bindParam(1, $return_value, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT);
$sth->execute();
print "procedure returned $return_value\n";
using this procedure
CREATE PROCEDURE `Insert_New_Return_Id`(IN Insert_Stmnt varchar(1000), OUT IDNum int)
BEGIN
SET #buffer = Insert_Stmnt;
PREPARE stmt FROM #buffer;
EXECUTE stmt;
SELECT LAST_INSERT_ID() INTO IDNum;
DEALLOCATE PREPARE stmt;
END
the following code works fine :
$statement=$con->prepare("CALL Insert_New_Return_Id (\"INSERT INTO users (first_name,last_name)VALUES('test','test')\",#ID)");
$statement->execute();
$statement=$con->query("SELECT #ID");
while ($row = $statement->fetch()){echo "Last ID Insert : " . $row['#ID'];}
but when i'm trying to bind parameters the values are ?
$first_name = "test";
$last_name = "test";
$statement=$con->prepare("CALL Insert_New_Return_Id (\"INSERT INTO users (first_name,last_name)VALUES('?','?')\",#ID)");
$statement->bindParam(1, $first_name, PDO::PARAM_STR);
$statement->bindParam(2, $last_name, PDO::PARAM_STR);
$statement->execute();
$statement=$con->query("SELECT #ID");
while ($row = $statement->fetch()){echo "Last ID Insert : " . $row['#ID'];}
If i try VALUES(?,?) returns an error.
How can i make this work? Call a procedure with prepare statement and binding parameters?
Thank you
$statement->bindParam(1, 'test', PDO::PARAM_STR);
$statement->bindParam(2, 'test', PDO::PARAM_STR);
You must use a variable instead of the string 'test'. PDOStatement::bindParam binds variables by reference. By definition, you cannot do this with a string.
Use a variable instead.
$statement->bindParam(1, $str1, PDO::PARAM_STR);
$statement->bindParam(2, $str2, PDO::PARAM_STR);
Also, when you want to use CALL to call a stored procedure, just call the stored procedure by name. Do not repeat the query. Of course, this assumes you've done the work of adding the stored procedure to MySQL.
$statement=$con->prepare('CALL Insert_New_Return_Id(?,?)');
If you need a third parameter, add it to the stored procedure in MySQL and call it like this.
$statement=$con->prepare('CALL Insert_New_Return_Id(?,?,?)');
As an example, suppose I want to execute the following query:
SELECT * FROM posts;
Therefore, I write the following:
CREATE DEFINER=`root`#`localhost` PROCEDURE `get_posts`(IN `zip` INT)
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
SELECT * FROM posts WHERE posts.zip = zip;
END
Is the following change the only one I have to make:
mysql_query("SELECT * FROM posts");
// to
mysql_query("CALL get_posts");
...and then I can fetch rows, etc.?
you also need to supply the parameter
mysql_query("CALL get_posts(11)");
another suggestion is by using PDO extension on this.
Example of using PDO,
<?php
$zipCode = 123;
$stmt = $dbh->prepare("CALL get_posts(?)");
$stmt->bindParam(1, $zipCode);
if ($stmt->execute(array($_GET['columnName'])))
{
while ($row = $stmt->fetch())
{
print_r($row);
}
}
?>
this will protect you from SQL Injection.
Your procedure expects an input parameter, so call it with one:
$result = mysql_query("CALL get_posts(12345)");
This will supply a result resource on a successful call, then you can run a fetch loop as you would a normal query.
if ($result) {
// fetch in a while loop like you would any normal SELECT query...
}