I've written a rather complex stored procedure in SQL Server 2012 that I know selects "1" multiple times when executed. When I run it in SQL Management Studio, it executes and the rows of my table update correctly. However, when I use the code below to call it from PHP, it's not executing:
$Month = 2;
$Year = 2016;
$connectionInfo = array("Database"=>"Finances", "UID"=>"sa", "PWD"=>"abcd1234");
$connection = sqlsrv_connect("localhost", $connectionInfo);
if( $connection === false ) {
die( print_r( sqlsrv_errors(), true));
}
$stmt = sqlsrv_prepare($connection, "exec UpdateBudgetToMatchTransactions #Month=?, #Year=?", array(&$Month, &$Year));
if (sqlsrv_execute($stmt) === false) {
die( print_r( sqlsrv_errors(), true));
}
SQL Profiler says the following is happening on the server:
declare #p1 int
set #p1=NULL
exec sp_prepexec #p1 output,N'#P1 int,#P2 int',N'exec UpdateBudgetToMatchTransactions #Month=#P1, #Year=#P2',2,2016
select #p1
go
However, the rows are not affected in the way they are when I call the stored procedure directly. Further, if I take that block of SQL and execute it in it's entirety in SQL Management Studio, the rows change how I'd expect them to.
I appreciate any assistance in determining what I'm doing wrong.
My master stored procedure did not include one line that was already in the sub procedures. I have added this line in the master stored procedure as well and now this behaves very well.
Have a look at adding "SET NOCOUNT ON" in the beginning of the procedure and give it a try !!
Related
I'm facing the problem while calling stored procedure by using sqlsrv drivers in laravel. Inside procedure there are multiple queries with combination of select and insert. I unable to share code here as its privacy issue.
So can any one please share the code which can work with laravel to call mssql procedure with multiple result row set.
Thanks in advance!!
MS SQL Server supports stored procedures that can return more than one result set. With PHP and PDO you can retrieve these result sets with PDOStatement::nextRowset() method. It is important to note, that if you have output parameters in your stored procedure, you need to fetch all result sets to get the output values.
If Laravel do not support nextRowset(), you may try to get the underlying PDO instance using the getPdo() method on a connection instance and use this instance for statement execution:
<?php
...
$pdo = DB::connection()->getPdo();
try {
$sql = "{CALL usp_TestProcedure(?)}";
$param = 'ParamValue';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(1, $param);
$stmt->execute();
do {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r($row, true);
echo '<br>';
}
} while ($stmt->nextRowset());
} catch( PDOException $e ) {
die( "Error executing query" );
}
...
?>
I can't get the OUTPUT parameter from my SQL Server (MSSQL 2012) SP to return to PHP. My Stored procedure is:
CREATE PROCEDURE spGetNextSeqID #ID AS INT OUTPUT
AS
BEGIN
BEGIN TRANSACTION
SELECT #ID = SEQUENCE_NO + 1 FROM tblCSRSequence WITH (TABLOCKX)
UPDATE tblCSRSequence SET SEQUENCE_NO=#ID
COMMIT TRANSACTION
END
And my PHP code is:-
<?php
include "DBConnect.php";
$conn = sqlsrv_connect( $serverName, $connection);
if( !$conn )
{
echo "Connection could not be established to ".$serverName;
die( print_r( sqlsrv_errors(), true));
}
$sql="{call dbo.spGetNextSeqID( ? )}";
$outSeq=0;
$params = array
(
array($outSeq, SQLSRV_PARAM_OUT)
);
$stmt = sqlsrv_query( $conn, $sql, $params );
if( $stmt == false)
die( print_r( sqlsrv_errors(), true) );
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn );
echo $outseq;
?>
I know the SP is getting called and working - I checked it with a trace and can see that it's generating the following:-
declare #p1 varchar(max)
set #p1='154'
exec dbo.spGetNextSeqID #p1 output
select #p1
Each time I refresh my browser page it calls the SP and increments the counter by 1 but never returns the value to the calling PHP function. I've been fiddling with this for about 2 days now - I've scoured the similar posts but none of the suggested fixes (like SET NOCOUNT ON etc) work.
Anyone got any ideas?
New:
I missed that you are using a single parameter as both input and output. Please try the following.
array($outSeq, SQLSRV_PARAM_INOUT)
Then using
sqlsrv_next_result($stmt);
echo $outSeq;
Reference:
http://technet.microsoft.com/en-us/library/cc644932(v=sql.105).aspx
Old:
You must set up $outSeq with the appropriate data type. Try initialize the value to $outSeq = 0.00, since your output type is MONEY.
Please reference the following article:
http://technet.microsoft.com/en-us/library/cc626303(v=sql.105).aspx
I am having trouble with this php code, the problem is that I have tried to insert 1000 rows on a Sql Server table but the code just inserts 80 rows and I do not know why, I have executed the Sql Server procedure alone on the Sql Server Management Studio and works good but when I try to execute from php It does not work, I also set the "remote query time out" to "no timeout". Here is the code that I am using. Help please.
PHP CODE
<?php
$myServer = "servername";
$conex=array("Database"=>"database");
$conn = sqlsrv_connect ($myServer, $conex) ;
if ( sqlsrv_begin_transaction( $conn ) === false ) {
die( print_r( sqlsrv_errors(), true ));
}
$sql="insertarDistrito_Sql ?";
$params=array(&$_POST(1000));
$stmt=sqlsrv_query($conn, $sql, $params);
if( $stmt) {
sqlsrv_commit( $conn );
echo "Transaction committed.<br />";
} else {
sqlsrv_rollback( $conn );
echo "Transaction rolled back.<br />";
}
?>
SQL SERVER STORED PROCEDURE
CREATE procedure [dbo].[insertarDistrito_Sql]
#cant int
As
Declare #i int
Declare #w int
Declare #id int
SET #i = 1
set #w=1
set #id=1
if (Select count(*) from distrito)> 0
begin
Set #id= (select max([id_distrito]) from [dbo].[distrito])
set #id=#id+1
end
WHILE(#i <= #cant)
BEGIN
INSERT INTO [dbo].[distrito] ([id_distrito], [id_warehouse], [d_nombre], [d_direccion], [d_calle1],
[d_calle2],[d_barrio], [d_fecha_creacion],[d_capacidad])
VALUES(#id,#w,newid(),newid(),newid(),newid(),newid(), '12/12/2014',rand())
SET #i += 1
set #id +=1
END
It could be PHP that is timing out, try putting
set_time_limit(0);
at the top of your PHP file.
I'm trying to learn more about MySQL and how to protect against SQL injections so my research has brought me to Prepared Statements which seems to be the way to go.
I'm also working on learning how to write Stored Procedures and am now trying to combine the two. There isn't much info on this though.
At the moment in my PHP test app I have a function that calls an SP with a normal MySQL command like this:
mysql_query("CALL usp_inserturl('$longurl', '$short_url', '$source')");
How can I do the same with MySQLi and a Prepared Statement to make it as safe as possible to injections?
Thanks!
Try the following:
$mysqli= new mysqli(... info ...);
$query= "call YourSPWithParams(?,?,?)";
$stmt = $mysqli->prepare($query);
$x = 1; $y = 10; $z = 14;
$stmt->bind_param("iii", $x, $y, $z);
$stmt->execute();
You can use both of them in the same time: just make preparation with stored procedure:
//prepare and bind SP's parameters with your variables only once
$stmt=$db->prepare("CALL MyStoredProc(?,?)");
$stmt->bind_param('is',$i,$name);
//then change binded variables and execute statement
for($i=1;$i<9;$i++)
{
$name="Name".$i;
$stmt->execute();
}
Bear in mind that you should do the preparation only once (not again for each execution), then execute it more times (just change parameter value before).
This one was a bit tricky but I eventually figured out how to both use a stored procedure (using IN parameters) that uses a prepared statement and retrieve the data through PHP. This example uses PHP 7.4.6 and MySQL 8.0.21 Community edition.
Here is the Stored Procedure:
CREATE DEFINER=`root`#`loalhost` PROCEDURE `SP_ADMIN_SEARCH_PLEDGORS`(
IN P_email VARCHAR(60),
IN P_password_hash VARCHAR(255),
IN P_filter_field VARCHAR(80),
IN P_filter_value VARCHAR(255)
)
BEGIN
#Takes admin credentials (first tow paramaters and searches the pledgors_table where field name (P_filter_field) is LIKE value (%P_filter_value%))
DECLARE V_admin_id INT(11);
BEGIN
GET DIAGNOSTICS CONDITION 1 #ERRNO = MYSQL_ERRNO, #MESSAGE_TEXT = MESSAGE_TEXT;
SELECT 'ERROR' AS STATUS, CONCAT('MySQL ERROR: ', #ERRNO, ': ', #MESSAGE_TEXT) AS MESSAGE;
END;
SELECT admin_id INTO V_admin_id FROM admin_table WHERE password_hash = P_password_hash AND email = P_email;
IF ISNULL(V_admin_id) = 0 THEN
SET #statement = CONCAT('SELECT pledgor_id, email, address, post_code, phone, alt_phone, contact_name
FROM pledgors_table
WHERE ',P_filter_field, ' LIKE \'%', P_filter_value, '%\';');
PREPARE stmnt FROM #statement;
EXECUTE stmnt;
ELSE
SELECT 'ERROR' AS STATUS, 'Bad admin credentials' AS MESSAGE;
END IF;
END
And here is the PHP script
query = 'CALL SP_ADMIN_SEARCH_PLEDGORS(\''.
strtolower($email).'\', \''.
$password_hash.'\', \''.
$filter_field.'\', \''.
$filter_value.'\');';
$errNo = 0;
//$myLink is a mysqli connection
if(mysqli_query($myLink, $query)) {
do {
if($result = mysqli_store_result($myLink)) {
while($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
mysqli_free_result($result);
}
} while(mysqli_next_result($myLink));
}
else {
$errNo = mysqli_errno($myLink);
}
mysqli_close($myLink);
You might find the following answer of use:
MySql: Will using Prepared statements to call a stored procedure be any faster with .NET/Connector?
In addition:
GRANT execute permissions only so your application level user(s) can only CALL stored procedures. This way, your application user(s) can only interact with the database through your stored procedure API, they can not directly:
select, insert, delete, update, truncate, drop, describe, show etc.
Doesn't get much safer than that. The only exception to this is if you've used dynamic sql in your stored procedures which I would avoid at all costs - or at least be aware of the dangers if you do so.
When building a database e.g. foo_db, I usually create two users. The first foo_dbo (database owner) is the user that owns the database and is granted full permissions (ALL) so they can create schema objects and manipulate data as they want. The second user foo_usr (application user) is only granted execute permisisons and is used from within my application code to access the database through the stored procedure API I have created.
grant all on foo_db.* to foo_dbo#localhost identified by 'pass';
grant execute on foo_db.* to foo_usr#localhost identified by 'pass';
Lastly you can improve your code example above by using mysql_real_escape_string:
http://php.net/manual/en/function.mysql-real-escape-string.php
$sqlCmd = sprintf("call usp_inserturl('%s','%s','%s')",
mysql_real_escape_string($longurl),
mysql_real_escape_string($shorturl),
mysql_real_escape_string($source));
$result = mysql_query($sqlCmd);
PHP 5.2.13, MS SQL Server 2008 R2
I have a stored procedure that looks something like this:
CREATE PROCEDURE [dbo].[StoreThing]
#pid int = 0,
#data binary(236) = NULL,
AS
BEGIN
INSERT INTO thingTable (pid, data) VALUES (#pid, #data)
END
(Greatly simplified, but that's beside the point)
I'm trying to call this procedure from a PHP script, as such:
function storeThing($pid, $data) {
global $dbconn;
if(strlen($data) != 236) return false;
$proc = mssql_init('StoreThing', $dbconn);
mssql_bind($proc, '#pid', $pid, SQLINT4);
mssql_bind($proc, '#data', $data, SQLCHAR, false, false, 236);
$result = mssql_execute($proc);
if(!$result) die(mssql_get_last_message());
return true;
}
However, this is not working quite right. I get the following error when I run it:
Warning: mssql_execute() [function.mssql-execute]: message: Implicit conversion from data type char to binary is not allowed. Use the CONVERT function to run this query. (severity 16)
Obviously, the problem is the SQLCHAR type I set for the data field. However, since there is no SQLBINARY constant, I am not sure what to set it to.
Alternately, will I have to change the stored procedure to accommodate PHP? I could do that, but it seems a bit dumb.
You can use the Microsoft SQL Server API, see http://msdn.microsoft.com/en-us/library/cc793139%28SQL.90%29.aspx