Avatar of darcher23
darcher23

asked on 

PHP Calling MS SQL Stored Procedures

Hi All,

I'm new to PHP and am banging my head against the wall in an effort to call an MS SQL stored procedure.  Any help would be appreciated!  I'm using currently the ADOdb abstraction layer.

This simple code should call a store procedure called procCountry_Upd.  This stored proc has two input paramters (@i32CountryID, and @strCountry).  If a value of @i32CountryID = 0 is passed, a record is added, however if an existing value is passed, then the record is updated.  The return value is always the record identity.

My current code is:

<?php
echo "about to connect<br>";
include('adodb/adodb.inc.php');
$db = &ADONewConnection("ado_mssql");      
print "<h1>Connecting DSN-less $db->databaseType...</h1>";                  
$myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};SERVER=myserver;DATABASE=mydatabase;UID=sa;PWD=;";
$db->Connect($myDSN);

$stmt = $db->PrepareSP("procCountries_Upd");
$db->InParameter($stmt,$CID,"i32CountryID");
$db->InParameter($stmt,$C,"strCountry");
$db->OutParameter($stmt,$NewID,"i32CountryIDNew");
$db->OutParameter($stmt,$ret,"RETVAL");

$CID = 0;
$C = "New Zealand";
$rs = $db->Execute($stmt);
if( !$rs ) {
print $db->ErrorMsg();
die;
}
echo "String = $ret\n";
echo $NewID

?>

The procedure works fine in Query Analyser, but when I execute the PHP page, all that happens is a blank record is inserted!!!!

The stored procedure code is:

ALTER PROCEDURE [dbo].[procCountries_Upd]
@i32CountryID AS INT = 0
, @strCountry AS NVARCHAR(50) = ''
, @i32CountryIDNew AS INT = 0 OUTPUT

AS
/**********************************************************************
Purpose :      Update/Insert for Countries tbl.
Notes   :      -
History  :      DJA      21-Apr-2006      Initial Creation.
**********************************************************************/
SET NOCOUNT ON
DECLARE @i32Error AS INT
DECLARE @i32TranCount AS INT

SET @i32Error = 0
SET @i32TranCount = @@TRANCOUNT

-- Update OR Insert ?
IF EXISTS (SELECT CountryID
            FROM Countries
            WHERE CountryID = @i32CountryID)
BEGIN
      UPDATE Countries
      SET Country = @strCountry
      WHERE CountryID = @i32CountryID
END
ELSE
BEGIN
      -- Insert.      
      
      INSERT INTO Countries
            (Country)
      VALUES (@strCountry)
END

SET @i32CountryIDNew = @@IDENTITY
RETURN @@IDENTITY
Microsoft SQL Server

Avatar of undefined
Last Comment
kamermans
Avatar of Aneesh
Aneesh
Flag of Canada image

Hi darcher23,

I am not goo at all PHP, anyway you can read the folowing article to check how to call an SP in php

http://www.sitepoint.com/print/php-microsoft-sql-server

Also, before doing  any modifications, to your existing code, run the sql profiler, then run your application and chck what statement is executing at the sql server end

Aneesh
Avatar of darcher23
darcher23

ASKER

Hi Aneesh,

Unfortunately the above link requires a PEAR database connection and this is a hosted server solution where I have no control over having PEAR installed.  Any other ideas?

Cheers,
David.
Avatar of nmcdermaid
nmcdermaid

This is more of a PHP syntax question, why don't you try posting in the PHP section?

A blank record - do you mean the identity value is created but the country value is blank?

That would imply that this line:

     INSERT INTO Countries
          (Country)
     VALUES (@strCountry)


Somehow has a blank value in @strCountry. Which seems to imply that the calling code is putting a blank value in, or the calling code isn't working quite right.

If you can connect with Profiler as previously suggested then you can check if this is the case.

You don't need PEAR libraries to run Profiler, you just need system admin priveliges in the database, a connection to the database, and the Profiler tool on your client.


I always had a lot of trouble with parameters in using ADO in VB, so I'm guessing the issue is in the PHP code. Have you been able to find an example of PHP code that does this?
Avatar of darcher23
darcher23

ASKER

Hi nmcdermaid,

I realised this was probably more a PHP syntax question after posting so have posted into that section (no responses yet - I think the PHP guys like using MySQL rather than MS SQL ;-) )

When I run the stored proc in Query Analyzer there is no problem, so I'm guessing it is more a problem with my PHP calling code.  I have actually managed to make this work by creating a string I can execute ...

// Database Operation
// Update a record in the countries table - return is updated record
$id = 11;
$C = "Aussie Land";

$result = $DbConn->Execute(" EXEC procCountries_Upd ".$id.", '".$C."' ");

$CountryID = $result->fields['CountryID'];
$Country = $result->fields['Country'];

                          while (!$result->EOF)
                          {
        echo $CountryID->value.' - '.$Country->value.'<BR>';
                          $result->MoveNext();
                          }
                         
$DbConn->Close();

However this approach isn't the neatest.

Cheers,
David.
Avatar of Aneesh
Aneesh
Flag of Canada image

I think better you move this question under the php section,

https://www.experts-exchange.com/Web/Web_Languages/PHP/PHP_Databases/
Avatar of PSSUser
PSSUser
Flag of United Kingdom of Great Britain and Northern Ireland image

I'm afraid I don't know PHP at all, but just scanning the code it looks to me the order of some ofyour lines is the cause of the problem.

Try moving the lines where you set the values of the variables:

$CID = 0;
$C = "New Zealand";

$db->InParameter($stmt,$CID,"i32CountryID");
$db->InParameter($stmt,$C,"strCountry");
$db->OutParameter($stmt,$NewID,"i32CountryIDNew");
$db->OutParameter($stmt,$ret,"RETVAL");

$rs = $db->Execute($stmt);
ASKER CERTIFIED SOLUTION
Avatar of kamermans
kamermans

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of darcher23
darcher23

ASKER

Hi Steve,

Thanks for your help.  I've used a variation of your suggestions and now have a working solutions.  I changed the stored procedure to return the newly inserted (or updated) record.

$DbConn->Open($strConnString);

// Database Operation
//insert a new record into the countries table - return is a new record
$id = 0;
$C = "New Country";

$result = $DbConn->Execute(" EXEC procCountries_Upd ".$id.", '".$C."' ");

$CountryID = $result->fields['CountryID'];
$Country = $result->fields['Country'];

                          while (!$result->EOF)
                          {
        echo $CountryID->value.' - '.$Country->value.'<BR>';
                          $result->MoveNext();
                          }
                         
$DbConn->Close();

I'm not sure that this the best way to integrate PHP and MS SQL Stored Procedures, but it seems to work well :-).

Cheers,
David.
Avatar of kamermans
kamermans

GranMod - Sorry about the link thing - you may want to cleanup some of my recent posts too then.  I will make sure I don't do that in the future!
Microsoft SQL Server
Microsoft SQL Server

Microsoft SQL Server is a suite of relational database management system (RDBMS) products providing multi-user database access functionality.SQL Server is available in multiple versions, typically identified by release year, and versions are subdivided into editions to distinguish between product functionality. Component services include integration (SSIS), reporting (SSRS), analysis (SSAS), data quality, master data, T-SQL and performance tuning.

171K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo